【发布时间】:2011-08-11 06:16:47
【问题描述】:
我的第一个插件使用适当的架构完成,但我一直坚持如何将事件侦听器应用于 $(window).scroll 以将 globalMessage 固定到窗口顶部。可以在此处查看完整的插件:https://gist.github.com/937792,但相关位是下面的 init。
设置修改目标元素的 css 属性的窗口事件侦听器的最佳方法是什么?
(function($){
var methods = {
init: function(options) {
var $this = this;
var opts = $.extend({}, $.fn.globalMessage.defaults, options);
var data = $this.data('globalMessage');
// init global data
if ( ! data ) {
$this.data('globalMessage', {
settings : opts
});
$(window).bind("scroll.globalMessage", function() {
// ----------
// HOW TO ACCESS both $this (defined outside this context)
// and the scrollTop value to change top css val?
//-----------
$this.css("top", $(window).scrollTop());
});
$this.bind('click.globalMessage', methods.hide);
}
return $this;
},
...[other funcs]...
}
...[main entry point etc]...
})(jQuery);
【问题讨论】:
-
我根本不清楚你的问题到底是什么。
-
也许我不明白你在用窗口滚动事件做什么,但是如果你想让 globalMessage 保持在窗口的顶部,你不能只使用 position:fixed css 吗?跨度>
-
@nicky - 假设您已将页面滚动到一半,并且您想要显示固定在窗口顶部的消息。在这种情况下,将不会看到带有 top:0 的固定元素。
-
@notbrain 也许你是对的,这里有点晚了 - jsfiddle.net/wUpgP
-
@nicky 你很清醒,看来我是缺少 css foo 的人;位置:固定是更好的方法。谢谢
标签: jquery plugins scope scrolltop