繁体   English   中英

Javascript(jQuery)Flasher效果:该怎么做?

[英]Javascript (jQuery) flasher effect: how to do that?

我想产生闪光效果:将鼠标悬停在某个指定字段上时会显示任何内容(在我的情况下为黄色图标),而当鼠标移开时它会消失。

问题是有很多类似的字段(将来会出现注释),所以我尝试将所有这些都放在一个循环中。 但这不起作用...我不知道为什么。

一些注意事项:我必须在没有html的情况下执行所有操作,而只能在javascript中进行操作,因此我使用了document.write方法。

jsfiddle上的演示

这里的代码:

var data = ['one', 'two', 'three'];
for(var i in data){
    (function(){
        $('#id'+i).mouseover(function(){    $("#hdn"+i).show();   });
        $('#id'+i).mouseout(function(){    $("#hdn"+i).hide();   });
    });
    document.write('<div id="id'+i+'" style="border:1px solid;margin:10px 0;float:left;width:100%;">');
        document.write('<div style="float:left;width:20px;height:20px;">'+data[i]+'</div>');
        document.write('<div id="hdn'+i+'" style="display:none;float:right;width:20px;height:20px;"><img src="http://t0.gstatic.com/images?q=tbn:ANd9GcSa7ebCG4VGWcTTXH8j7ebfpFWhYuV9ojisNmsrnZaQHk8wRMTNqGfaNA" /></div>')
    document.write('</div>');
}

谢谢!

您需要在写出html 之前设置事件处理程序。 那行不通。

另外,JavaScript中的for循环为您提供数组的索引,而不是实际值。

最好的方法是为html设置div,将此html添加到其中,然后让jQuery将div添加到您的身体。

var newHtml = "";
for(var i = 0; i < data.length; i++) {
    newHtml += '<div id="id'+i+'" style="border:1px solid;margin:10px 0;float:left;width:100%;">';
        newHtml += '<div style="float:left;width:20px;height:20px;">'+data[i]+'</div>';
        newHtml += '<div id="hdn'+i+'" style="display:none;float:right;width:20px;height:20px;"><img src="http://t0.gstatic.com/images?q=tbn:ANd9GcSa7ebCG4VGWcTTXH8j7ebfpFWhYuV9ojisNmsrnZaQHk8wRMTNqGfaNA" /></div>';
    newHtml += '</div>';
}

var newDiv = $("<div />");
$("body").append(newDiv);
$(newDiv).html(newHtml);

for(var i = 0; i < data.length; i++) {
    (function(){
        $('#id'+i).mouseover(function(){    $("#hdn"+i).show();   });
        $('#id'+i).mouseout(function(){    $("#hdn"+i).hide();   });
    });
var data = ['one', 'two', 'three'];

$.each(data,function(i,v) {
    $('<div id="id'+i+'" style="border:1px solid;margin:10px 0;float:left;width:100%;">')
        .append('<div style="float:left;width:20px;height:20px;">'
                 +v+'</div><div id="hdn'
                 +i+'" style="display:none;float:right;width:20px;height:20px;"><img src="http://t0.gstatic.com/images?q=tbn:ANd9GcSa7ebCG4VGWcTTXH8j7ebfpFWhYuV9ojisNmsrnZaQHk8wRMTNqGfaNA" /></div>')
        .appendTo('body')
        .mouseover(function(){    $(this).children('[id^="hdn"]').show();   })
        .mouseout(function(){    $(this).children('[id^="hdn"]').hide();   });
});

如果使用类名而不是ID,则可以一口气影响多个元素。 另外,不要使用document.write ,而是更新现有元素的innerHTML。

$('#outputDIV').html("....")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM