Rot*_*075 12 javascript jquery
我得到一个关于如果对象在我的屏幕内将被调用的函数的问题.但是当对象在我的屏幕内时,该函数被调用并且已触发警报.但是,如果我关闭警报并向下滚动,则会再次调用该事件.我不要那个.我怎么解决这个问题?
我的代码到目前为止:
<div id="wrapper">
scroll down to see the div
</div>
<div id="tester"></div>
Run Code Online (Sandbox Code Playgroud)
JS
$(window).on('scroll',function() {
if (checkVisible($('#tester'))) {
alert("Visible!!!")
} else {
// do nothing
}
});
function checkVisible( elm, eval ) {
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}
Run Code Online (Sandbox Code Playgroud)
我想要的是If函数只会被调用一次,如果对象可见则不会在每个滚动上调用.
Pra*_*man 23
尝试使用.one():
$(window).one('scroll',function() {
// Stuff
});
Run Code Online (Sandbox Code Playgroud)
或者,取消内部事件的链接:
$(window).on('scroll',function() {
// After Stuff
$(window).off('scroll');
});
Run Code Online (Sandbox Code Playgroud)
猜猜你可能需要这个代码:
$(window).on('scroll',function() {
if (checkVisible($('#tester'))) {
alert("Visible!!!");
$(window).off('scroll');
} else {
// do nothing
}
});
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/c68nz3q6/
让我们尝试在javascript中解决您的问题,因为这里的所有答案都在jquery中.只要页面未刷新,您就可以使用全局变量,因为浏览器会保留其值.在函数外部声明的所有变量都称为全局变量,可以由任何函数访问.
window.onscroll = myScroll;
var counter = 0; // Global Variable
function myScroll(){
var val = document.getElementById("value");
val.innerHTML = 'pageYOffset = ' + window.pageYOffset;
if(counter == 0){ // if counter is 1, it will not execute
if(window.pageYOffset > 300){
alert('You have scrolled to second div');
counter++; // increment the counter by 1, new value = 1
}
}
}Run Code Online (Sandbox Code Playgroud)
#wrapper,#tester {
width: 300px;
height: 300px;
border: 1px solid black;
padding: 10px;
}
#wrapper p {
text-align: center;
}
#tester {
border: 1px solid crimson;
}
#value {
position: fixed;
left: auto;
right: 40px;
top: 10px;
}Run Code Online (Sandbox Code Playgroud)
<p id = "value"></p>
<div id="wrapper">
<p>scroll down to div to see the alert</p>
</div>
<div id="tester"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24895 次 |
| 最近记录: |