我似乎无法弄清楚这一点.我有一个div,里面有一些文字.当用户选择它的部分(完全随机,无论他们想要什么)时,我想要一个小弹出窗口内的文本.
为了主动弹出,我可以这样做吗?...
$('#textdiv').click(function() {
Run Code Online (Sandbox Code Playgroud)
但是,我如何才能获得所选/突出显示的文本?
Ble*_*der 12
jQuery在这里没有多大用处,所以你需要纯JS来做选择抓取部分(信用转到这个页面):
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
你和mouseup处理程序在正确的轨道上,所以这就是我的工作:
$('#test').mouseup(function() {
var selection = getSelected();
if (selection) {
alert(selection);
}
});
Run Code Online (Sandbox Code Playgroud)
还有一个现场演示:http://jsfiddle.net/PQbb7/7/.
小智 6
刚刚更新了第一个答案。尝试这个
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
/* create sniffer */
$(document).ready(function() {
$('#my-textarea').mouseup(function(event) {
var selection = getSelected();
selection = $.trim(selection);
if(selection != ''){
$("span.popup-tag").css("display","block");
$("span.popup-tag").css("top",event.clientY);
$("span.popup-tag").css("left",event.clientX);
$("span.popup-tag").text(selection);
}else{
$("span.popup-tag").css("display","none");
}
});
});Run Code Online (Sandbox Code Playgroud)
.popup-tag{
position:absolute;
display:none;
background-color:#785448d4;
color:white;
padding:10px;
font-size:20px;
font-weight:bold;
text-decoration:underline;
cursor:pointer;
-webkit-filter: drop-shadow(0 1px 10px rgba(113,158,206,0.8));
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Select any text :<br>
<textarea type="text" id="my-textarea" style="width:100%; height:200px;" >
While delivering a lecture at the Indian Institute of Management Shillong, Kalam collapsed and died from an apparent cardiac arrest on 27 July 2015, aged 83. Thousands including national-level dignitaries attended the funeral ceremony held in his hometown of Rameshwaram, where he was buried with full state honours.
</textarea>
<span class="popup-tag"></span>Run Code Online (Sandbox Code Playgroud)
见:https://jsfiddle.net/arunmaharana123/kxj9pm40/
| 归档时间: |
|
| 查看次数: |
7126 次 |
| 最近记录: |