滚动后,javascript选定文本未正确定位

时间:2015-06-21 17:39:44

标签: javascript html css angularjs

我想通过选择文字让我的用户进行搜索。选择文本后,在所选文本右侧打开一个新按钮,用于提供搜索选项。当用户滚动到页面底部时,搜索按钮未正确定位。我的代码如下:

HTML:

 <body ng-app="newsApp"  ng-controller="NewsCtrl" ng-mouseup="showSelectedText($event)">  

     <!-- user search button -->
     <div ng-show="isUserSearch" ng-style="{ 'left' : leftPos, 'top': rightPos, 'display': displayState }" class="searchBtn">
        Search             
     </div>

     <!-- main content -->
     <div>
       <!-- main content -->
    </div>

 </body>

的CSS ::

.searchBtn {
    position: absolute;
    padding: 4px 7px;
    background-color: #ff0;
    color: #ddd;
    z-index: 9999;
    border-radius: 5px 5px 5px 5px;
    height: 27px;
    cursor: pointer;
 }

的javascript ::

angular.module('newsApp',  [])

   .controller('NewsCtrl',function ($scope) {

       $scope.leftPos = "-200px";
       $scope.rightPos = "-200px";
       $scope.displayState = "none !important";
       $scope.isUserSearch = false;

       $scope.selectedTextSearch = "";

       $scope.showSelectedText = function($event) {
          $scope.selectedText =  "";

          if (window.getSelection) {
             $scope.selectedText = window.getSelection().toString();
          } 
         else if (document.selection && document.selection.type != "Control") {
             $scope.selectedText = document.selection.createRange().text;
          }

          if($scope.selectedText.length > 0)    {            
             $scope.leftPos = (+$event.clientX + 5) + 'px';   
             $scope.rightPos = ( +$event.clientY - 15 ) + 'px';  
             $scope.isUserSearch = true;
          } else {
             $scope.isUserSearch = false;
          }
       };

   });

Plunker

我现在能做什么?

1 个答案:

答案 0 :(得分:1)

clientX更改为pageX

$scope.leftPos = (+$event.pageX + 5) + 'px';   
$scope.rightPos = ( +$event.pageY - 15 ) + 'px'; 

请参阅this answer了解差异。