问题
How to alert when scroll page only first time using javascript ?
I want to alert only first scroll page, How can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(window).scroll(function() {
var xxx;
if (xxx === '') {
var xxx = "test";
var div = $("#myDiv");
alert(div.height());
}
});
</script>
<DIV id="myDiv" style="height:auto; width:78;overflow:hidden"> Simple Test</DIV>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
回答1:
Use .one()
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
$(window).one("scroll", function() {
console.log("foo");
});
Code snippet:
$(window).one("scroll", function() {
console.log("foo");
});
div {
height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo</div>
回答2:
Put you variable as global and use boolean instead of string which is a better practice when using code flags.Besides, no need to re-define you variable when setting it within the scroll function.
var xxx;
$(window).scroll(function () {
if(!xxx)
{
xxx = true;
var div = $("#myDiv");
alert(div.height());
}
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<DIV id="myDiv" style="height:auto; width:78;overflow:hidden"> Simple Test</DIV>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
回答3:
onscroll = function () {
var xxx = "test";
var div = $("#myDiv");
alert(div.height());
onscroll = null; // remove function so wont get called next time
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<DIV id="myDiv" style="height:auto; width:78;overflow:hidden"> Simple Test</DIV>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
来源:https://stackoverflow.com/questions/31637069/how-to-alert-when-scroll-page-only-first-time-using-javascript