获取所选文本的ID

时间:2016-12-17 04:53:21

标签: javascript

我正在用PHP-MySQL做一个小项目。在Web预览中,有一些带有ID的div。 div包含文本。我的问题是在选择文本的某些部分时找到div中文本的div-id,文本长度和位置。用javascript可以吗?请帮我。提前致谢。

  <!DOCTYPE html>
 <!-- Latest compiled and minified JavaScript -->
  <script    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>

  <style type="text/css">
  .custom-menu {
display: none;
z-index: 1000;
position: absolute;
overflow: hidden;
border: 1px solid #CCC;
white-space: nowrap;
font-family: sans-serif;
background: #FFF;
color: #333;
border-radius: 5px;
padding: 0;
}

  /* Each of the items in the list */
     .custom-menu li {
padding: 8px 12px;
cursor: pointer;
list-style-type: none;
transition: all .3s ease;
       }

 .custom-menu li:hover {
background-color: #DEF;
 }


  #overlay {
 visibility: hidden;
 position: absolute;
 left: 0px;
 top: 0px;
 width:100%;
 height:100%;
  z-index: 1000;
   }

   #overlay div {
 width:300px;
 margin: 100px auto;
 background-color: #fff;
 border:1px solid #000;
 padding:15px;

   }

       </style>

         <?php 
        include("../viewmodel/PriviewModel.php");
         include("../include/header.php");
       $privewmodel = new PriviewModel();
     if(isset($_SESSION["preview"])) {$privewmodel = $_SESSION["preview"];}

       $count=0;

        foreach($privewmodel->getTOPIC_NAME() as $topicname)
          {
          if($count==0) {
        echo $topicname .'<br/><ul>';
          }

        else 

         {

    echo '<li>'.$topicname.'</li>';

        }
       $count++;

       }
       ?>
      </ul>  

       <div style="padding: 2%">
      <?php
      $count=0;
      foreach($privewmodel->getTOPIC_TEXT() as $topictext)
         {
         if($count==0) {
       echo '<b>ভূমিকাঃ </b><br/><div id="'.$count.'" readonly rows="15"                  cols="150">'.$topictext .'</div><br/>';
        }

       else 

        {

 echo '<div id="'.$count.'" readonly rows="15" cols="150">'.$topictext.'</div><br/><br/>';

          }
        $count++;

         }
          ?>

         </div>
        <div id="overlay">
           <div>
     <form name="addhyperlink" method="post" action="../controller/UpdatePreviewController.php">

          <?php     foreach($privewmodel->getOnlytopic() as $topicname)
              {

       echo '<input type="radio" value="'.$topicname->topic_id.'" name="hyperlink" required/> '.$topicname->topic_name.'<br/>' ;


             } ?>
          <input id="sel" type="hidden" name="seltext" value="">    
         <input type ="submit">      
     </form>
     </div>
     </div>
    <ul class='custom-menu'>
    <li data-action="first">Add hyperlink</li>
     <li data-action="second">Add embeded media</li>
    <li data-action="third">Add kichu ekta</li>
     </ul>


        <script>

       // JAVASCRIPT (jQuery)

       // Trigger action when the contexmenu is about to be shown
         $(document).bind("contextmenu", function (event) {
          var text = getSelectionText();

           if(text!='')

             { 
      // Avoid the real one   
         event.preventDefault();

             // Show contextmenu
            $(".custom-menu").finish().toggle(100).

           // In the right position (the mouse)
          css({
    top: event.pageY + "px",
    left: event.pageX + "px"
});


      document.getElementById("sel").value = text;


              }
       });


      // If the document is clicked somewhere
      $(document).bind("mousedown", function (e) {

  // If the clicked element is not the menu
  if (!$(e.target).parents(".custom-menu").length > 0) {

    // Hide it
    $(".custom-menu").hide(100);
        }
           });


        // If the menu element is clicked
       $(".custom-menu li").click(function(){

// This is the triggered action name
switch($(this).attr("data-action")) {

    // A case for each action. Your actions here
    case "first": addhyperlink(); break;
    case "second": alert("second"); break;
    case "third": alert("third"); break;
}

// Hide it AFTER the action was triggered
$(".custom-menu").hide(100);
          });


       function addhyperlink()
       {
  el = document.getElementById("overlay");
  el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
    t = (document.all) ? document.selection.createRange().text : document.getSelection();



     }

       function getSelectionText(){
var selectedText = "";
if (window.getSelection){ // all modern browsers and IE9+
    selectedText = window.getSelection().toString();
         }
return selectedText;
      }



       function getdivID()
          {
  var ID = window.getSelection().valueOf("id"); 

  alert(ID); // here lies the problem
         }


     </script>

        <?php include("../include/footer.php");?>

1 个答案:

答案 0 :(得分:0)

这是html代码

<input id="sel" type="hidden" name="seltext" value=""> 
<input id="selid" type="hidden" name="selid" value=""> 
<input id="selstartpos" type="hidden" name="selstartpos" value=""> 
<input id="selendpos" type="hidden" name="selendpos" value=""> 
<input type ="submit"> 

并且指定的精确定位的javascript代码是

  <script>

  // JAVASCRIPT (jQuery)

  // Trigger action when the contexmenu is about to be shown
 $(document).bind("contextmenu", function (event) {
  var text = getSelectionText();
  var id = getSelectionParentElement();
  var selrange = getSelectionCharOffsetsWithin(id);

  if(text!='')

    { 
      // Avoid the real one   
     event.preventDefault();

    // Show contextmenu
    $(".custom-menu").finish().toggle(100).

    // In the right position (the mouse)
   css({
    top: event.pageY + "px",
    left: event.pageX + "px"
    });


   document.getElementById("sel").value = text;
   console.log(id);
  document.getElementById("selid").value = id.id;
  document.getElementById("selstartpos").value = selrange.start;
  document.getElementById("selendpos").value = selrange.end;

    }
  });

  // If the document is clicked somewhere
  $(document).bind("mousedown", function (e) {

  // If the clicked element is not the menu
  if (!$(e.target).parents(".custom-menu").length > 0) {

    // Hide it
    $(".custom-menu").hide(100);
    }
  });


 // If the menu element is clicked
   $(".custom-menu li").click(function(){

   // This is the triggered action name
   switch($(this).attr("data-action")) {

    // A case for each action. Your actions here
    case "first": addhyperlink(); break;
    case "second": alert("second"); break;
    case "third": alert("third"); break;
   }

   // Hide it AFTER the action was triggered
   $(".custom-menu").hide(100);
  });


 function addhyperlink()
  {
    el = document.getElementById("overlay");
    el.style.visibility = (el.style.visibility == "visible") ? "hidden" :   "visible";
    t = (document.all) ? document.selection.createRange().text : document.getSelection();



     }

  function getSelectionText(){
   var selectedText = "";
   if (window.getSelection){ // all modern browsers and IE9+
    selectedText = window.getSelection().toString();
    }
   return selectedText;
    }



    function getSelectionCharOffsetsWithin(element) {
    var start = 0, end = 0;
    var sel, range, priorRange;
     if (typeof window.getSelection != "undefined") {
    range = window.getSelection().getRangeAt(0);
    priorRange = range.cloneRange();
    priorRange.selectNodeContents(element);
    priorRange.setEnd(range.startContainer, range.startOffset);
    start = priorRange.toString().length;
    end = start + range.toString().length;
     } else if (typeof document.selection != "undefined" &&
        (sel = document.selection).type != "Control") {
    range = sel.createRange();
    priorRange = document.body.createTextRange();
    priorRange.moveToElementText(element);
    priorRange.setEndPoint("EndToStart", range);
    start = priorRange.text.length;
    end = start + range.text.length;
     }
     return {
    start: start,
     end: end
      };
      }

   function getSelectionParentElement() {
    var parent = null,
    selection;
     if (window.getSelection) {
    selection = window.getSelection();
    if (selection.rangeCount) {
        parent = selection.getRangeAt(0).commonAncestorContainer;
        if (parent.nodeType != 1) {
            parent = parent.parentNode;
        }
    }
} else if ((selection = document.selection) && selection.type != "Control") {
    parent = selection.createRange().parentElement();
}
return parent;
 }
</script>