Javascript: onmouseover function

Javascript: onmouseover function

本文关键字:function onmouseover Javascript      更新时间:2023-09-26

我有一个问题,改变动态图片的onmouseover和onmouseout属性。我想要它的工作方式是,每当我把鼠标放在图像上,图像必须改变,当我把鼠标拿走时,它必须改变为原始图片。每当我选择任何图像时,该图像必须更改为在图像上移动鼠标时显示的图像。当我选择任何其他图像时,同样的过程必须发生,但是之前更改的图像必须更改回原始图像。

我已经完成了上述所有,但我的问题是,当我选择多个图片,并把我的鼠标放在以前选择的图像,这些图像不改变(onmouseover属性不再对它们起作用)。

<script language="javascript">
    function changeleft(loca){
        var od=''
        var imgs = document.getElementById("leftsec").getElementsByTagName("img"); 
        for (var i = 0, l = imgs.length; i < l; i++) {  
            od=imgs[i].id;
            if(od==loca){
                imgs[i].src="images/"+od+"_over.gif";
                imgs[i].onmouseover="";
                imgs[i].onmouseout="";
            }else{
                od = imgs[i].id;
                imgs[i].src="images/"+od+".gif";
                this.onmouseover = function (){this.src="images/"+od+"_over.gif";};
                    this.onmouseout = function (){this.src="images/"+od+".gif";};
            }
        }
    }
</script>
<div class="leftsec" id="leftsec" >
    <img id='wits' class="wits1"  src="images/wits.gif" onmouseover="this.src='images/wits_over.gif'" onmouseout="this.src='images/wits.gif'" onclick="changeleft(this.id)" /><br />
    <img id='city' class="city1" src="images/city.gif" onmouseover="this.src='images/city_over.gif'" onmouseout="this.src='images/city.gif'" onclick="changeleft(this.id)" /><br />
    <img id='organise' class="city1" src="images/organise.gif" onmouseover="this.src='images/organise_over.gif'" onmouseout="this.src='images/organise.gif'" onclick="changeleft(this.id)" /><br />
    <img id='people' class="city1" src="images/people.gif" onmouseover="this.src='images/people_over.gif'" onmouseout="this.src='images/people.gif'" onclick="changeleft(this.id)" /><br />
</div>

我建议使用Ajax库(jQuery, YUI, dojo, ExtJS,…)。在jQuery中,我会这样做:

Edit:扩展.click()能力的例子

var ignoreAttrName = 'data-ignore';
var imgTags = jQuery('#leftsec img'); // Select all img tags from the div with id 'leftsec'
jQuery(imgTags)
.attr(ignoreAttrName , 'false') // Supplying an ignore attribute to the img tag
.on('click', function () {
    jQuery(imgTags).attr(ignoreAttrName, 'false'); // Resetting the data tag
    jQuery(this).attr(ignoreAttrName, 'true'); // only the current will be ignored
    // Do whatever you want on click ...
})
.on('mouseover', function () {
    // This will be called with the img dom node as the context
    var me = jQuery(this);
    if (me.attr(ignoreAttrName) === 'false') {
        me.attr('src', me.attr('id') + '.gif');
    }
})
.on('mouseout', function () {
    // This will be called when leaving the img node
    var me = jQuery(this);
    if (me.attr(ignoreAttrName) === 'false') {
        me.attr('src', me.attr('id') + '-over.gif');
    }
});

有了一个库,我认为它更干净,更可扩展,并且它在其他浏览器中工作的机会也增加了:)。

希望这对你有所帮助!