[英]How to Change jQuery to Fire On Page Load
好的,這似乎應該很簡單,但我無法弄清楚。 我從另一位開發人員那里獲得了這段代碼,我負責將其更改為在頁面加載而不是滾動時觸發。 我已經嘗試過將所有我能想到的東西(例如將.bind
更改為.load
和jQuery(this).bind('inview', function(event,visible)
更改$(document).ready(function()
),但沒有任何效果,該怎么做才能使這些數字僅在初始頁面加載時進行動畫處理?
// Animate any number
jQuery('.animateNumber').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = jQuery(this).text();
value = parseInt(value);
// Set the starting text to 0
jQuery(this).text('0');
// Animate to correct value
jQuery(this).bind('inview', function(event,visible) {
if(visible == true) {
jQuery(this).animateNumber(
{
number: value,
},
1000
)
}
});
});
更新
我已將代碼更改為以下代碼,並且在Firefox中可以正常工作,但在Chrome中不能進行動畫處理。 有人知道為什么會這樣嗎?
// Animate any number
jQuery('.animateNumber').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = jQuery(this).text();
value = parseInt(value);
// Set the starting text to 0
jQuery(this).text('0');
// Animate to correct value
jQuery(this).animateNumber(
{
number: value
},
1000
);
});
只需將其包裝成文檔即可
$(document).ready(function() {
//Your code
});
編輯:查看您的代碼,看起來像:
jQuery(this).bind('inview', function(event,visible) {
每次使該元素可見時都會被觸發,因此當您上下滾動時,該函數將再次運行...我建議您刪除該元素,並將if語句添加到它的下面,使您的代碼如下所示:
// Animate any number
jQuery('.animateNumber').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = jQuery(this).text();
value = parseInt(value);
// Set the starting text to 0
jQuery(this).text('0');
// Animate to correct value
jQuery(this).animateNumber(
{
number: value,
},
1000
);
如果它破壞了其他功能,您還可以創建一個全局變量,以防止其執行多次:
var numbersAnimate = true;
// Animate any number
jQuery('.animateNumber').each(function(){
var value = new Number;
// Grab contents of element and turn it into a number
value = jQuery(this).text();
value = parseInt(value);
// Set the starting text to 0
jQuery(this).text('0');
// Animate to correct value
jQuery(this).bind('inview', function(event,visible) {
if(visible == true && numbersAnimate == true) {
numbersAnimate = false;
jQuery(this).animateNumber(
{
number: value,
},
1000
)
}
});
雖然,我不建議使用它,但最多不過是臨時解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.