代码之家  ›  专栏  ›  技术社区  ›  Donkey Shame

将示例jQuery函数转换为vanilla JS:Element.offsetTop存在明显问题

  •  0
  • Donkey Shame  · 技术社区  · 7 年前

    我甚至不确定我到底在问什么,所以请容忍我。

    我正试图复制这种效果 this 酷笔来自 Krz Szzz

    以下是原始jQuery:

       $('.tile')
        // tile mouse actions
         .on('mouseover', function(){
          $(this).children('.photo').css({'transform': 'scale('+ $(this).attr('data- 
       scale') +')'});
        })
        .on('mouseout', function(){
          $(this).children('.photo').css({'transform': 'scale(1)'});
        })
        .on('mousemove', function(e){
        $(this).children('.photo').css({'transform-origin': ((e.pageX - 
        $(this).offset().left) / $(this).width()) * 100 + '% ' + ((e.pageY - 
        $(this).offset().top) / $(this).height()) * 100 +'%'});
        })
    

    here's 我试图将jQuery本土化(我试图降低复杂性以关注手头的问题,因此我的标记与他/她的标记有点不同,但我不相信相关的方式)。

    var tile = document.querySelector('.tile');
    var tileWidth = tile.offsetWidth;
    var tileHeight = tile.offsetHeight;
    var tileTop = tile.offsetTop;
    var tileLeft = tile.offsetLeft;
    
    tile.addEventListener('mouseover', function(){
      tile.style.transform = "scale(1.5)";
    });
    
    tile.addEventListener('mousemove', function(e){
      tile.style.transformOrigin = ((e.pageX - tileLeft) / tileWidth) * 100 + "%" + ((e.pageY - tileTop) / tileHeight) * 100 + "%";
    });
    
    tile.addEventListener('mouseout', function(){
      tile.style.transform = "scale(1)";
    });
    

    我的版本半途而废。但是,其中的某个地方存在计算错误,从而无法为第二个参数设置正确的值 transform-origin

    这个问题与 $(this).offset().top 在jQuery中。我已将此转换为 Element.offsetTop

    0 回复  |  直到 7 年前
        1
  •  1
  •   emanuelpoletto    7 年前

    jQuery offset().top() 获取与 而js offsetTop .

    Element.getBoundingClientRect().top 试试看。

    它将为您提供与 ,而不是 文件 . 但这只是一个开始。

    document.documentElement.scrollTop 把它们加起来。


    document.documentElement.scrollTop document.body.scrollTop