0

我有一张图片,上面有几个 javascript 调用,其中大部分都可以正常工作。

基本上,我想要它做的是,当单击交换图像时,然后根据它当前所在的图像,也可以在鼠标悬停时交换。

这是我的 HTML:

<a href="#show" class="show_hide">
<img src="<?php echo WEB_URL; ?>/images/show-more-arrow.jpg" width="61" height="45" id="clicktoggleimage" onclick="changeImage()" onMouseOver="checkMouseOver()" onMouseOut="checkMouseOut()" /></a>

还有我的 Javascript:

function changeImage() {
    if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-less-arrow.jpg") {
        document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-more-arrow.jpg";
    } else {
        document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-less-arrow.jpg";
    }
}

function checkMouseOver() {
    if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-less-arrow.jpg") {
        document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-less-arrow-over.jpg";
    } else if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-more-arrow.jpg") {
        document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-more-arrow-over.jpg";    
    }
}

function checkMouseOut() {
    if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-less-arrow-over.jpg") {
        document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-less-arrow.jpg";
    } else if (document.getElementById("clicktoggleimage").src == "http://www.pete.com/images/show-more-arrow-over.jpg") {
        document.getElementById("clicktoggleimage").src = "http://www.pete.com/images/show-more-arrow.jpg"; 
    }
}

这工作正常,除非第二次单击按钮时,图像不会恢复为 show-less-arrow.jpg

非常感谢您的帮助

4

1 回答 1

1

You can make this JS a lot more efficient.

Since it appears you're only replacing 'more' with 'less' and vice versa, in your changeImage function, that is exactly what your function should do. The mouse over/off is only toggling the '-over' section of your string.

So, remove the event listeners from your HTML:

<a href="#show" class="show_hide">
    <img src="<?php echo WEB_URL; ?>/images/show-more-arrow.jpg" width="61" height="45" id="clicktoggleimage" />
</a>

And use this Javascript:

var img = document.getElementById("clicktoggleimage");

function changeImage() {
    if (img.src.indexOf('less') == -1) {
        img.src = img.src.replace('more', 'less');
    } else {
        img.src = img.src.replace('less', 'more');
    }
}

function hoverImage() {
    if (img.src.indexOf('arrow-over') == -1) {
        img.src = img.src.replace('arrow', 'arrow-over');
    } else {
        img.src = img.src.replace('arrow-over', 'arrow');
    }
}

img.onclick = cangeImage;
img.onmouseover = img.onmouseout = hoverImage;
于 2013-01-09T11:47:48.913 回答