假设我选择了一些文字。我希望<div>
出现在所选文本的开头。
到目前为止,我有代码来跟踪所选文本:
$(document).ready(function() {
$("#actual_verse").mouseup(function() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
if (/\S/.test(text)) {
alert(text);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='actual_verse'> A justo sit aut sit sed. Wisi a cras sed. Feugiat mus nulla sagittis proin, feugiat accumsan turpis neque, velit nec odio bibendum, cum dui mi turpis interdum, aptent risus vestibulum eu vitae sed. Nulla facilisis, id quis cubilia vel suscipit, fermentum ante aliquam nunc. Scelerisque lacinia, ut molestie dui libero arcu elit nec, faucibus tenetur maecenas sit ipsum rutrum. Non amet erat non sit quis, nonummy magna elit integer in sed in, suspendisse quis velit blandit, interdum quam dui mollis vestibulum elementum, urna donec eros eget. Mauris aliquam montes a, sem est sed, eveniet lacus nibh, donec ornare sit, aptent sit rutrum gravida. Wisi et amet lobortis. </span>
如何在所选文字的开头显示<div>
?
答案 0 :(得分:0)
答案 1 :(得分:0)
如果你想在选择开始的位置放置一个div,你可以这样做:
$(document).ready(function() {
$('.conttext').mouseup(function() {
var highlight = window.getSelection();
var spn = '<span class="highlight">' + highlight + '<div class="mydiv"></div></span>';
var text = $('.conttext').text();
$('.conttext').html(text.replace(highlight, spn));
});
});
&#13;
.highlight {
position: relative;
}
.mydiv {
position: absolute;
top: 0;
left: 0;
height: 100px;
width: 100px;
background-color: gold;
z-index: -1;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="conttext">How hard can it be to achieve this here and now. Will it be difficult or can it be done with great simplicity</div>
&#13;