js页面文字选中后分享实现

眉间皱痕 提交于 2020-03-23 12:43:45
var $sinaMiniBlogShare = function(eleShare, eleContainer) {
    var eleTitle = document.getElementsByTagName("title")[0];
    eleContainer = eleContainer || document;
    var funGetSelectTxt = function() {
        var txt = "";
        if(document.selection) {
            txt = document.selection.createRange().text;    // IE
        } else {
            txt = document.getSelection();
        }
        return txt.toString();
    };
    eleContainer.onmouseup = function(e) {
        e = e || window.event;
        var txt = funGetSelectTxt(), sh = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
        var left = (e.clientX - 40 < 0) ? e.clientX + 20 : e.clientX - 40, top = (e.clientY - 40 < 0) ? e.clientY + sh + 20 : e.clientY + sh - 40;
        if (txt) {
            eleShare.style.display = "inline";
            eleShare.style.left = left + "px";
            eleShare.style.top = top + "px";
        } else {
            eleShare.style.display = "none";
        }
    };
    eleShare.onclick = function() {
        var txt = funGetSelectTxt(), title = (eleTitle && eleTitle.innerHTML)? eleTitle.innerHTML : "未命名页面";
        if (txt) {
            window.open('http://v.t.sina.com.cn/share/share.php?title=' + txt + '→来自页面"' + title + '"的文字片段&url=' + window.location.href);    
        }
    };
};

假设新浪微博分享图标的HTML如下:

<img id="imgSinaShare" class="img_sina_share" title="将选中内容分享到新浪微博" src="http://simg.sinajs.cn/blog7style/images/common/share.gif" />

则直接:

$sinaMiniBlogShare(document.getElementById("imgSinaShare"));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!