簡體   English   中英

對同一頁面上的多個圖像使用相同的 javascript

[英]Use the same javascript for multiple images on the same page

我有一堆想要放在同一頁面上的圖像對。 我希望能夠使用相同的外部 javascript 代碼在每對圖像之間切換,即不必為每個項目重復代碼。

下面的代碼非常適合使用數據屬性在一對圖像之間切換,但我將如何 go 再次對同一頁面上的不同圖像對使用相同的代碼?

<html>

<head>
    
<div id='urls' data-image1='https://www.dropbox.com/s/79pypzinnvyk36u/apple.jpg?raw=1' data-image2='https://www.dropbox.com/s/2zmsaqhal9ettus/banana.jpg?raw=1'></div>

<script>
    
    var images = document.getElementById('urls');
        var src1 = images.getAttribute('data-image1');
        var src2 = images.getAttribute('data-image2');
    
    function changeImage() {

        if (document.getElementById("imgClickAndChange").src == src2)
        {
            document.getElementById("imgClickAndChange").src = src1;
        }
        else 
        {
            document.getElementById("imgClickAndChange").src = src2;
        }
    }
</script>

</head>
    
    <body>
        <p>
        <img alt="" src="https://www.dropbox.com/s/79pypzinnvyk36u/apple.jpg?raw=1" 
            style="width: 100%; max-width:800px; height: auto; border: 0;" id="imgClickAndChange" onclick="changeImage()" />
        </p>
    </body>


</html>```

您當前的 function 僅針對特定圖像元素。 但是,如果您查看這些 MDN 文檔: event.currentTarget ,您可以訪問在事件處理程序回調中觸發元素的標簽。

I prefer the addEventListener syntax but you can also pass in 'this' in your onClick function call and then access the event object in your changeImage() function to get your toggle behaviour.

我在onClick function中傳遞了我需要的參數。

<html>

<head>
    

<script>
    
    
    function changeImage(src1, src2,imgID) {

        if (document.getElementById(imgID).src == src2)
        {
            document.getElementById(imgID).src = src1;
        }
        else 
        {
            document.getElementById(imgID).src = src2;
        }
    }
</script>

</head>
    
    <body>
        <p>
        <img alt="" src="https://www.dropbox.com/s/79pypzinnvyk36u/apple.jpg?raw=1" 
            style="width: 100%; max-width:800px; height: auto; border: 0;" id="appleBanana" onclick="changeImage('https://www.dropbox.com/s/79pypzinnvyk36u/apple.jpg?raw=1','https://www.dropbox.com/s/2zmsaqhal9ettus/banana.jpg?raw=1','appleBanana' )" />
        </p>
        
                <p>
        <img alt="" src="https://www.dropbox.com/s/o5khsr21jvec69n/tomato.jpg?raw=1" 
            style="width: 100%; max-width:800px; height: auto; border: 0;" id="tomatoCucumber" onclick="changeImage('https://www.dropbox.com/s/o5khsr21jvec69n/tomato.jpg?raw=1','https://www.dropbox.com/s/zejo8o19c8ropco/cucumber.jpg?raw=1','tomatoCucumber')" />
        </p>
        
    </body>


</html>```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM