douxing9813 2017-04-07 16:39
浏览 40

我的PHP变量源图像被破坏了

My end goal is to have an image that swaps to a different image when the window scrolls past a certain point. I started with JavaScript to get the whole scroll position and set the if/else statement.

<script type="text/JavaScript">
    function checkHeight() {
        currentScrollPos = window.scrollY;

        if (currentScrollPos < 325)
            document.getElementById('test1').innerHTML = "../wp-content/uploads/2017/04/LOGO-1.png";
        else if (currentScrollPos > 325)
            document.getElementById('test1').innerHTML = "../wp-content/uploads/2017/04/LOGO-1-alt.png";
    }
</script>

<p id="test1"></p>

All of that worked flawlessly. The inner HTML contents of the <p id="test1"></p> displayed the correct image source and swapped said source when I scrolled. Perfect.

Finally, I went to place that image source as the actual source of an <img> and that's where I hit a wall. I tried to use a simple PHP variable.

<?php
$src = <<<END
<p id="test1"></p>
END;
?>

And that worked. I could echo that $src and it displayed the image source correctly as before. So I proceeded, and I put it into the following code.

<img src='<?php echo $src; ?>' />

But nothing. It seems like it works to an extent except it's showing me a broken image symbol when I load up the page. Why is it not finding my image files? Am I missing something stupid?

  • 写回答

1条回答 默认 最新

  • duanji8615 2017-04-07 17:05
    关注

    The new, working code. Sorry about wasting all of your time and being a complete moron.

    <script type="text/JavaScript">
    
    function checkHeight() {
        currentScrollPos = window.scrollY;
    
        if (currentScrollPos < 325)
            document.getElementById('image').src = "../wp-content/uploads/2017/04/LOGO-1.png";
        else if (currentScrollPos > 325)
            document.getElementById('image').src = "../wp-content/uploads/2017/04/LOGO-1-alt.png";
    }
    </script>
    
    <body onload="checkHeight();" onScroll="checkHeight();"></body>
        <img id="image" width="200px" />
    
    评论

报告相同问题?