简体   繁体   中英

javascript selected text is not properly positioned after scroll

I want to let my user to search by selecting text. After selecting text, a new button open on right of the selected text for giving an option to search or not. when user scroll to bottom on the page, search button is not properly positioned. My code is given below:

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

What can I do now?

Change clientX to pageX

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

See this answer for the difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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