繁体   English   中英

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

[英]javascript selected text is not properly positioned after scroll

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

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

我现在能做什么?

更改clientXpageX

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

看到这个答案的区别。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM