JQuery with css3 keydown keyCode = 37 and 39

JQuery with css3 keydown keyCode = 37 and 39

本文关键字:and keyCode with css3 keydown JQuery      更新时间:2023-09-26

我已经测试了这两种方法。Jquery动画和css3过渡,css3稍微快一点。但我有一个问题与以下代码:

 $(document).keydown(function(e){
if (e.keyCode == 39) { 
    var DocHeight = $(document).height();
    $('.container').css("margin-top","-="+DocHeight)
}
});

如果我点击两次keyCode 39(箭头向右),那么我的过渡是外层空间。有人能解决这个问题吗?

外层空间

可能不是正确的词。但问题是。如果我按两次箭头键,我将得到最后一个请求,换句话说…动画开始了,另一个动画从我不想要的位置开始。

示例:hit #1 margin-top从0px变为1024px。但是当我点击它两次的时候,margin-top的位置是23px,并在1047px停止。

这不是我想要的。它必须在1024px处停止。

试一下:

$(document).keydown(function(e) {
    var DocHeight = $(document).height();
    if (DocHeight > 1024) {
        $('.container').css("margin-top", "1024px")
    } else {
        if (e.keyCode == 39) {
            $('.container').css("margin-top", "-=" + DocHeight)
        }
    }
});

此代码仅检查DocHeight是否大于1024。

在这里找到一个演示:http://jsfiddle.net/shawn31313/fRYwM/
我使用$('.container').css("margin-top", "+=" + DocHeight)为例,但使用它与-也将工作。

编辑:(我知道你不需要它):

我编辑了代码,所以它的工作效果是原来的两倍:

$(document).ready(function() {
    check();
});
$(document).keydown(function(e) {
    var DocHeight = $(document).height();
    if (DocHeight > 1024) {
        $('.container').css("margin-top", "1024px")
    } else {
        if (e.keyCode == 39) {
            if (DocHeight > 1024) {
                $('.container').css("margin-top", "1024px")
            }
            $('.container').css("margin-top", "+=" + DocHeight)
        }
    }
});
$(document).keyup(function(e) {
    var DocHeight = $(document).height();
    if (DocHeight > 1024) {
        $('.container').css("margin-top", "1024px")
    }
});
function check() {
    if (DocHeight > 1024) {
        $('.container').css("margin-top", "1024px")
    }
    check();
}

这个示例是:http://jsfiddle.net/shawn31313/fRYwM/1/

Try

var mTop = 0;
$(document).keydown(function(e){
  if (e.keyCode == 39) { 
    var DocHeight = $(document).height();
    mTop = mTop - parseInt(DocHeight);
    $('.container').css("margin-top", mTop);
  }
});

这只是继续,如果你只想让它动画一次然后停止,试试这样做:

var mTop = 0;
$(document).keydown(function(e){
  if (e.keyCode == 39) { 
    var WinHeight = $(window).height();
    mTop = parseInt(WinHeight);
    $('.container').css("margin-top", -mTop);
  }
});

在移动带有边距的内容时使用文档高度是一个坏主意,而且每次只是用"-="将文档高度添加到css中会导致问题,当你在动画完成之前点击按钮时,它会添加一个介于两者之间的值,你应该在变量中进行计算,并使用该变量来设置css的一致性

如果你使用jquery animate,那么你可以使用.is(":animated")只开始一个新的动画,如果一个还没有在进行

var $container = $('.container');
if (e.keyCode == 39 && !$container.is(":animated")) { 
    var DocHeight = $(document).height();
    $container.animate(...)
}

这只会在动画还没有开始时才会开始。