[英]JavaScript - I condition “if” doesn't respond properly
这是代码背后的想法:本文开头有一个头像对象。 例如:
<div class="column-right">
<div class="inner">
<h3>Header of article</h3>
<div id="avatar">
<img>
<div>avatar title</div>
</div>
<p>long text</p>
</div>
</div>
当用户向下滚动时,化身显然消失了。 所以我想克隆一个化身,并使用位置fixed
将其放在左栏中。
这是JavaScript代码:
document.body.onscroll = function(e) {
var scrolled = document.documentElement.scrollTop;
var newAv;
if ( (scrolled > avatarCoords.bottom) && !newAv ) {
//check if user scrolled below the avatar. if clone of avatar exists, do anything:
newAv = avatar.cloneNode(true);
//clone actual element, whick user can't see right now
newAv.style.position = "fixed";
newAv.style.left = 2 + "px";
newAv.style.top = 10 + "px";
document.body.appendChild(newAv); //add clone in document
}
if( (scrolled < avatarCoords.bottom) && newAv ) {
newAv.parentNode.removeChild(newAv);
}
}
function getCoords(element) {
var box = element.getBoundingClientRect();
return {
bottom: box.top + avatar.offsetHeight
}
}
我不明白为什么即使分配了变量newAv ,第一个条件仍然保持响应。 !newAv
在第一次克隆后应该为假。
如果您可以回答第一个问题,请告诉我为什么newAv
无法删除newAv
。
谢谢!
您继续在onscroll函数中重新定义newAV。
将其设置为全局变量(这样就可以记住上一次调用的值):
var newAv;
document.body.onscroll = function(e) {
var scrolled = document.documentElement.scrollTop; // etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.