我在我的网站上写了一些javascript,当它们出现在视图中时会逐渐消失。但它的效率非常低。
<script type="text/javascript" charset="utf-8">
$(function () {
$('a.reposition.r1').bind('inview', function (event, visible) {
if (visible) {
$("a.reposition.r1").css({"opacity": "1", "transition": "1s"});
} else {
$("a.reposition.r1").css({"opacity": "0", "transition": "1s"});
}
});
$('a.reposition.r2').bind('inview', function (event, visible) {
if (visible) {
$("a.reposition.r2").css({"opacity": "1", "transition": "1s"});
} else {
$("a.reposition.r2").css({"opacity": "0", "transition": "1s"});
}
});
$('a.reposition.r3').bind('inview', function (event, visible) {
if (visible) {
$("a.reposition.r3").css({"opacity": "1", "transition": "1s"});
} else {
$("a.reposition.r3").css({"opacity": "0", "transition": "1s"});
}
});
});
</script>
我试着让它更紧凑,像这样:
<script type="text/javascript" charset="utf-8">
$('a.reposition').bind('inview', function (event, visible) {
if (visible) {
$("a.reposition").css({"opacity": "1", "transition": "1s"});
} else {
$("a.reposition").css({"opacity": "0", "transition": "1s"});
}
});
</script>
但是现在所有元素在用户将第一个元素滚动到视口中时淡入。我希望每个元素在移动到视口时单独淡入。怎么办呢?
答案 0 :(得分:4)
使用this
获取当前正在调用的元素
$('a.reposition').bind('inview', function (event, visible) {
if (visible) {
$(this).css({"opacity": "1", "transition": "1s"});
} else {
$(this).css({"opacity": "0", "transition": "1s"});
}
});
并摆脱重复的代码:
$('a.reposition').bind('inview', function (event, visible) {
var opacity = visible ? "1" : "0";
$(this).css({"opacity": opacity, "transition": "1s"});
});