簡體   English   中英

我的腳本需要頁面刷新才能運行

[英]My script needs page refresh for it to run

每次我第一次不加載腳本時都加載頁面時,我需要刷新頁面至少3次才能運行。 如何在不刷新頁面的情況下運行腳本? 該特定腳本在BABEL中。

'use strict';

var deg = 0;
var index = 0;

$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
    return false;
});
$('.navbar').on('mousewheel', function (e) {
    var move = -60;
    var nextIndex = nextIndex = (index + 1) % 6;
    if (e.originalEvent.wheelDelta / 120 <= 0) {
        // wheel up
        move = 60;
        nextIndex = index  -1 < 0 ? 5 : index - 1;
    }
    $('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
    $('#' + index).css('opacity', '0.01');
    $('#' + nextIndex).css('opacity', '1');
    index = nextIndex;
    deg = deg + move;
    event.stopPropagation();
    console.timeEnd('cache');
});

如果將代碼包裝在window.onload函數中怎么辦?

window.onload = function() { 
  // your code
}

僅當html文檔“就緒”且已完全加載時,您的代碼才會運行。

您正在運行依賴於頁面元素的Javascript,並且在元素出現在頁面上之前就執行了javascript;

在document.ready函數中包裝所有代碼

$(document).ready(function () {
var deg = 0;
var index = 0;

$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
    return false;
});
$('.navbar').on('mousewheel', function (e) {
    var move = -60;
    var nextIndex = nextIndex = (index + 1) % 6;
    if (e.originalEvent.wheelDelta / 120 <= 0) {
        // wheel up
        move = 60;
        nextIndex = index - 1 < 0 ? 5 : index - 1;
    }
    $('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
    $('#' + index).css('opacity', '0.01');
    $('#' + nextIndex).css('opacity', '1');
    index = nextIndex;
    deg = deg + move;
    event.stopPropagation();
    console.timeEnd('cache');
});
});

將代碼包裝在ready函數中,以便在加載DOM之后執行JavaScript。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM