获得用户选中内容,判断是否分享
HTML结构
<p id="word1">
此处省略一堆文字
</p>
<p id="word2">
此处省略一堆文字
</p>
<div id="panel"></div>
<span id="sina"></span>
Css样式
<style>
* {
margin: 0;
padding: 0;
border: 0;
}
p {
margin: 50px;
width: 300px;
}
#panel {
background-color: skyblue;
width: 150px;
color: orangered;
position: absolute;
display: none;
}
#sina {
width: 26px;
height: 26px;
background: url("images/share.gif");
position: absolute;
display: none;
}
</style>
Js代码
<script>
window.onload = function () {
var wordOne = document.getElementById('word1');
var wordTwo = document.getElementById('word2');
var panel = document.getElementById('panel');
var sina = document.getElementById('sina');
var selectedText = '';
wordOne.onmouseup = function (event) {
var event = event || window.event;
selectedPanel(false);
}
wordTwo.onmouseup = function (event) {
var event = event || window.event;
selectedPanel(true);
}
function selectedPanel(isShare) {
if (window.getSelection) {
selectedText = window.getSelection();
// alert(selectedText)
}
else {
selectedText = document.selection.createRange().text.toString();
}
// 不分享到微博
var share = sina;
if (!isShare) {
share = panel;
share.innerHTML = selectedText;
}
if (selectedText != '') {
share.style.display = 'block';
share.style.left = event.clientX + 'px';
share.style.top = event.clientY + 'px';
}
document.onmousedown = function (event) {
var event = event || window.event;
var targetId = event.target ? event.target.id : event.srcElement.id;
if (targetId != 'panel') {
panel.style.display = 'none';
}
if (targetId != 'sina') {
sina.style.display = 'none';
}
else {
window.location.href = 'http://v.t.sina.com.cn/share/share.php?searchPic=false&title=' + selectedText + '&url=https://www.baidu.com';
}
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}
}
}
</script>
特效展示
选中内容分享
网友评论