0

你好朋友我设计了一个浮动 div 并且它工作得很好但由于某些原因我不想在我的代码中使用position:relativeposition:absolute

$(window).scroll(function () {

        var topWindowPosition = $(window).scrollTop();
        var leftWindowPosition = $(window).scrollLeft();
        var topLeftNavHeight = 200;
        if (topWindowPosition >= topLeftNavHeight) {
            $("#scroll").css({ top: topWindowPosition - topLeftNavHeight, left: 0, position: 'relative' });
        } else {
            $("#scroll").css({ top: 0, left: 0, position: 'relative' });
        }
        $("#scroll").forceRedraw();
    });

您还可以在此处查看工作演示

http://jsfiddle.net/9E225/1/

我可以在不使用职位的情况下做出同样的效果吗?请帮帮我。

提前致谢

4

2 回答 2

3

当然,只需使用margins而不是positions. 例如:

if (topWindowPosition >= topLeftNavHeight) {
    $("#scroll").css({ marginTop: topWindowPosition - topLeftNavHeight, marginLeft: 0});
} else {
    $("#scroll").css({ marginTop: 0, marginLeft: 0 });
}

jsfiddle:http: //jsfiddle.net/9E225/2/

于 2012-04-04T11:22:22.790 回答
1

我不知道你对这种方法感觉如何。当元素超出滚动元素时,它会将元素捕捉到位,并在返回时立即返回。这种方法的主要优点是您的#scroll元素不会在每个触发的滚动事件上“跳回”并重新定位自己。

示例| 代码

var $el = $("#scroll");
var original_top = $el.position().top;

$(window).scroll(function () {
    //Scrolled past element
    if($(window).scrollTop() >= original_top){
        //Add hooked element, if it's not already hooked
        if(!$el.hasClass("hooked")) $el.addClass("hooked");
    }else if($(window).scrollTop() <= original_top){
        //Scrolled up before element, remove hooking and return back to normal
        if($el.hasClass("hooked")) $el.removeClass("hooked");
    }
});

CSS

.hooked{
    position: fixed;
    top: 0;
    left: 0;
}

另外,我建议您看看这个“JQuery Waypoints”库。它的运行方式与上述代码相同,但功能更多。:)

于 2012-04-04T11:34:44.330 回答