我想通过每个人来获取图像大小。通过高度和宽度,我可以设置div“.text-person-show”的高度和宽度。
$(window).load(function () {
$(".person").each(function () {
var h = $(this).find(".person-image").height();
var w = $(this).find(".person-image").width();
$(this).hover(function () {
alert(w);
$(this).find(".person-image").toggle();
$(this).find(".text-person").toggle();
$(this).find(".text-person").toggleClass("text-person-show", 'add');
$(".text-person-show").width(w).height(h);
});
});
});
HTML:
<div class="person">
<div class="person-post">
<div class="person-image"> <img src="<?php the_field('image'); ?>"></div>
<div class="text-person">
<div class="text-inner">
<div class="name-person-text-inner"><?php the_title(); ?>
</div>
</div>
</div>
</div>
问题是:为什么我只获得第一个“.person”的警报(w)? 我现在不明白!变量范围?
很多Thx !!!
答案 0 :(得分:2)
尝试下面的代码并使用.on事件进行未来事件,并删除每个循环。
$(window).load(function () {
$('.person').on('hover', function () {
var h = $(this).find(".person-image").height();
var w = $(this).find(".person-image").width();
alert(w);
$(this).find(".person-image").toggle();
$(this).find(".text-person").toggle();
$(this).find(".text-person").toggleClass("text-person-show", 'add');
$(".text-person-show").width(w).height(h);
});
});
旁注根据David Thomas的建议: -
on()已经从1.7版本的jQuery中可用(此时 live()已被弃用)。在1.7之前的jQuery jQuery团队中 建议,在方法本身的API文档中使用 委托()。 live()有很多问题(链接, 事件冒泡和表现),即使在哪里也不应该使用 它是可用的(除非文件中的权衡取舍 方法得到承认)。