【问题标题】:Scroll to top an image in sidebar angularjs directive滚动到侧边栏 angularjs 指令中的图像顶部
【发布时间】:2016-06-06 06:32:35
【问题描述】:

我需要使用 angularjs 指令将活动图像滚动到顶部。当我尝试使用 element[0].offset() 处理时,它的抛出错误。

解释:

在这里,我将活动元素硬编码为行中的 5。无需为此编写代码,因为我可以根据 url 动态设置活动元素。我需要的只是图像 5 应该滚动到侧栏的顶部,因为它是活动元素

myApp.controller('sidebarController', function($scope){
$scope.images=[];
for(var i = 0; i< 10; i++){
    temp = {url:'http://lorempixel.com/400/200',active:false}
    $scope.images.push(temp)
}

$scope.images[5].active=true;  // hardcoding the 5th element to be active.

})

这是我的指令代码。

myApp.directive('scrollToTop',function($timeout){

return {
    restrict:'A',
    link:function(scope, element, attributes){
    if(attributes.active == true || attributes.active =='true'){
    $timeout(function () {
            console.log(element)
        //angular.element(element)[0].scrollTop =  element[0].offset().top;// commented it as it was throwing error.
      });
    }
  }  
}

})

这是我的jsfiddle

【问题讨论】:

    标签: angularjs scroll directive


    【解决方案1】:

    经过 2 天的编码,使用了 anchorScroll。希望这应该是唯一的解决方案。困惑 scrollTop 是干什么用的?

    这是我的updated Code

    myApp.directive('scrollToTop',function($timeout, $anchorScroll, $location){
    
    return {
        restrict:'A',
        link:function(scope, element, attributes){
                if(JSON.parse(attributes.scrollToTop.toLowerCase())){
            $location.hash(attributes.id);
            $anchorScroll();
            }
      }  
    }
    
    })
    

    【讨论】:

      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 2020-09-09
      • 2020-12-06
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2014-07-25
      • 2023-02-23
      相关资源
      最近更新 更多