jQuery为小屏幕禁用数据滚动速度

时间:2018-12-26 05:27:04

标签: javascript jquery

我才刚刚开始学习JavaScript / jQuery,并且试图禁用我的代码以缩小屏幕宽度。我拥有的代码(感谢教程)正在改变html中特定元素的滚动速度:

<div id="text1" data-scroll-speed="3">
            <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div id="text2" data-scroll-speed="2">
            <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>

这是使其工作的代码:

$.fn.moveIt = function () {
    var $window = $(window);
    var instances = [];

    $(this).each(function () {
        instances.push(new moveItItem($(this)));
    });

    window.onscroll = function () {
        var scrollTop = $window.scrollTop();
        instances.forEach(function (inst) {
            inst.update(scrollTop);
        });
    }
}

var moveItItem = function (el) {
    this.el = $(el);
    this.speed = parseInt(this.el.attr('data-scroll-speed'));
};
moveItItem.prototype.update = function (scrollTop) {
    this.el.css('transform', 'translateY(' + -(scrollTop / this.speed) + 'px)');
};

// Initialization
$(function () {
    $('[data-scroll-speed]').moveIt();
});

例如,我只希望此代码在屏幕宽度小于770px时停止工作。我研究了如何做到这一点的多种方法,并尝试了许多方法,但是我做得不好(因为我是一个真正的新手……)。如果有人可以向我展示可行的解决方案,我将不胜感激。这是我尝试过的一个例子。谢谢,祝你有美好的一天!

   $(document).ready(function(){
    $('[data-scroll-speed]').moveIt(){
        if ($(window).width() > 770) {

 $.fn.moveIt = function () {
    var $window = $(window);
    var instances = [];

    $(this).each(function () {
        instances.push(new moveItItem($(this)));
    });

    window.onscroll = function () {
        var scrollTop = $window.scrollTop();
        instances.forEach(function (inst) {
            inst.update(scrollTop);
        });
    }
}var moveItItem = function (el) {
    this.el = $(el);
    this.speed = parseInt(this.el.attr('data-scroll-speed'));
};
moveItItem.prototype.update = function (scrollTop) {
    this.el.css('transform', 'translateY(' + -(scrollTop / this.speed) + 'px)');
};
        }
    }
});

1 个答案:

答案 0 :(得分:0)

您可以在div内使用style条件

if

如何将这部分代码添加到您的代码中

onscroll