【JavaScript】 得到文字框中被滑鼠選中的字

  • 2748
  • 0

最近曾經有一個需求,井底之蛙的我還想說,騙人的吧!!這做不到。

說說這個需求吧!

Web介面中,textarea輸入了一堆SQL指令(請注意SQL Inject問題)。

可以像SSMS般,執行使用者反白的那個區域的指令。

找了公司的前端,給了我關鍵字,就發現真的可以喔!!只是,還是無法百分之百相同。

而且,瀏覽器需支援Html5

搬出stackoverflow。果然,找到很多解法。

參考:參考1    Javascript trigger selection start

關鍵的解決點在於:

  • selectionStart 、selectionEnd 兩個property。
  • 觸發時機

我在Plunker寫了一個模擬出來的結果

      <textarea id="txtsqlCommand" row="3"></textarea>
      <p>
        Selection Command:
      </p>
      <pre><p id="command"></p></pre>
      <input type="hidden" id="txtSelectCommand"/>
      <p><button id="btnExec">執行</button></p> 

在textarea輸入後,如果有特定指定要執行的區段,透過滑鼠移動選取,選取後會顯示在id=command的地方。

按下執行按鈕,會判斷是否有特定要執行區段,沒有的話則則為整個textarea指令。

// Add your javascript here
$(function(){
  var m_MouseDown = false;
  
  document.getElementById('txtsqlCommand').onmousedown = function (e) {
    m_MouseDown = true;
  };

  document.getElementById('txtsqlCommand').onmouseup = function (e) {
    m_MouseDown = false;
  };

  document.getElementById('txtsqlCommand').onmousemove = function(e) {
    if (m_MouseDown) {
        $("#command").html(getText());
    }        
  }
  
  function getText() {
    var elem = document.getElementById('txtsqlCommand');
        return elem.value.substring(elem.selectionStart,
                                    elem.selectionEnd);
  }
  
  $("#btnExec").click(function(){
    if(!$("#command").html())
    {
      var allCommand = $("#txtsqlCommand").val();
      $("#txtsqlCommand").val(allCommand);
      $("#txtSelectCommand").val(allCommand);
    }
    else{
      $("#txtSelectCommand").val($("#command").html());
    }
    
    $("#command").html('');
    alert("Execed:" + $("#txtSelectCommand").val());
  });


});

JavaScript部分,我們用註冊一系列的mouse動作,來決定抓取文字的時機。

同時註冊按下執行按鈕的事件。

整個UI就大抵完成了。

最後,這樣的動作,千萬要小心SQL Injection。