gpt4 book ai didi

javascript - 如何为html类添加事件监听器?

转载 作者:可可西里 更新时间:2023-11-01 02:54:49 31 4
gpt4 key购买 nike

如果我有这样的 HTML:

<a href="#" class="movieImg"><div class="previewBulk"></div></a>
<a href="#" class="movieImg"><div class="previewBulk"></div></a>

和这样的 Javascript:

var movie = document.getElementsByClassName("movieImg");
var preview = document.getElementsByClassName("preview");

有什么方法可以addEventListener 2 movie a 标签和预览div 标签吗?我尝试循环,但是当我做类似的事情时:

for(var i = 0, j=movie.length; i<j; i++){
movie[i].style.left = 100;
preview[i].style.left = 100;
}

我收到 Uncaught TypeError: Cannot read property 'style' of undefined

preview改为previewBulk后还是报错,其实我的代码是这样的

(function(){
var movie = document.getElementsByClassName("movieImg"),
preview = document.getElementsByClassName("previewBulk");
//result = [];

for(var i = 0, j=movie.length; i<j; i++){
movie[i].addEventListener("mouseover", function(){

preview[i].style.left = ((movie[i].offsetWidth-preview[i].offsetWidth)/2)+20;
preview[i].style.top = -(movie[i].offsetHeight+preview[i].offsetHeight);
preview[i].style.visibility = "visible";
});

movie[i].addEventListener("mouseout", function(){
preview[i].style.visibility = "hidden";
});
}
}());

最佳答案

document.getElementsByClassName 不返回数组。它返回一个像 XML 文件一样遍历的节点列表。

    <a href="#" class="movie"><div class="previewBulk"></div></a>
<a href="#" class="movie"><div class="previewBulk"></div></a>

<script>

var movie = document.getElementsByClassName("movie");

for(var i = 0; i<movie.length; i++){
movie.item(i).style.width = "100px";
}​

</script>

参见 jsfiddle:http://jsfiddle.net/Uy5fk/

关于javascript - 如何为html类添加事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6762557/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com