首页 > > > 尝试写一个回到顶部的插件但是无法给元素绑定事件
1 (function($) {
2 $.fn.scrollto = function(options) {
3 // 将用户传递的参数去覆盖默认的参数然后返回一个新的对象
4 this.opts = $.extend({}, $.fn.scrollto.defaults, options);
5 console.log(this);
6 return this.each(function() {
7 $this = $(this);
8 // $this.fadeOut();
9 console.log($this);
10 $root = $('html,body');
11 console.log($root);
12 var opts = $.extend({}, $.fn.scrollto.defaults, options);
13 console.log(opts);
14 // checkpos($this,opts);
15
16 $(window).on('scroll', checkpos($this, opts));
17
18 if (opts.mode == 'move') {
19 $this.on("click", move(opts));
20 } else {
21 $this.on("click", go(opts));
22 }
23
24 });
25
26
27
28 };
29
30 // private function
31 function checkpos(obj, opts) {
32 console.log($(window).scrollTop());
33 // document.title=$(window).scrollTop();
34 if ($(window).scrollTop() > opts.pos) {
35 obj.fadeIn();
36 } else {
37 obj.fadeOut();
38 }
39 }
40
41
42 // private function
43 function move(opts) {
44 console.log(this);
45 // var opts = this.opts,
46 // dest = opts.dest;
47 if ($(window).scrollTop() !== opts.dest) {
48 if (!this.$root.is(':animated')) {
49 $root.animate({
50 scrollTop: opts.dest
51 }, opts.speed);
52 }
53 }
54 }
55
56 // paivate function
57 function go(opts) {
58 console.log(this);
59 var dest = opts.dest;
60 if ($(window).scrollTop() != dest) {
61 $root.animate({
62 scrollTop: dest,
63 });
64 }
65 }
66
67 $.fn.scrollto.defaults = {
68 pos: $(window).height(),
69 dest: 0,
70 speed: 800,
71 mode: 'move'
72 };
73 })(jQuery);
74
75
76 $("#backTop").scrollto({
77 mode: 'move'
78 });事件只运行一次,而且控制台看不到绑定的事件
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4547/viewspace-3128624/ ,如需转载,请注明出处,否则将追究法律责任。