你了解getBoundingClientRect()?

理解:getBoundingClientRect用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性。

1.语法:这个方法没有参数。

rectObject = object.getBoundingClientRect();

2.返回值类型:
 rectObject.top:元素上边到视窗上边的距离;

 rectObject.right:元素右边到视窗左边的距离;

 rectObject.bottom:元素下边到视窗上边的距离;

 rectObject.left:元素左边到视窗左边的距离;

  

3.思考 :这个属性在ie5就开始支持,能做什么呢? 在淘宝 京东 支付宝 里面可见的效果 。

4.如下效果:

 

5.Html:

 

6.逻辑:

(function ($) {

 function myScroll(element, option) {

     this.element = element;
     
     this.setting = $.extend({}, option, myScroll.defaults)

     

     this.init();

    
 }
 
 myScroll.defaults = {
     
     fixed: {
         "position": "fixed",
         "top": 0,
         "z-index": 1000,
         
     },
     
     none: {
         "position": "relative",
         "z-index": 0
     }
 }

 myScroll.prototype = {
     init: function () {

         var target = this.setting.target;
         var fixed = this.setting.fixed;
         var none = this.setting.none;
         var element = this.element;
        
         $(window).scroll(function () {
             var obj = document.getElementById(target.slice(1)).getBoundingClientRect();

             if (obj.top - $(this.element).height() < 0 && obj.bottom - $(this.element).height() > 0) {

                 $(element).css(fixed)
                
                 $(element).css("width",$(element).parent().width()+"px")
                 
                 
             } else {

                 $(element).css(none)

             }
         });
     },
    
     
 }
 function myPlugin(option) {

     return this.each(function () {
         var that = $(this)
         var data = that.data('bs')
         var options = typeof option == 'object' && option

         that.data('bs', new myScroll(this, options))

     })
 }

 $.fn.myScroll = myPlugin
 $.fn.myScroll.Constructor = myScroll



 $(window).on('load', function () {
     $('[data-type="top"]').each(function () {

         var type = $(this)

         myPlugin.call(type, type.data())

     })
 })


   })(jQuery)

作者:原型设计
链接:https://www.jianshu.com/p/824eb6f9dda4
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
posted @ 2019-05-27 16:56  追求极致  阅读(607)  评论(0编辑  收藏  举报