美文网首页
选中文字-分享效果

选中文字-分享效果

作者: TsingXu | 来源:发表于2016-08-15 14:41 被阅读0次

    知识点:

    1. document.selection.createRange().text
    2. window.getSelection().toString()
    3. onmouseup
    4. window.event
    5. clientX / clientY
    6. cancelBubble
    效果图

    html代码:

    <body>
    <p id="p1">
    【玩转大连必做的10件事】漫步滨海路、到海滨浴场享受阳光海滩、在人民广场喂鸽子、看女骑警、坐一回有轨电车、回忆老时光、走旅顺、忆国之殇民族之痛、老虎滩看海豚白鲸、漫步街头聆听建筑交响乐、吃海鲜大餐、渔人码头看夕阳...欢迎补充!
    </p>
    <div id="div1"><img src="images/share.gif" /></div>
    </body>
    

    1. 获取元素

    var oP = document.getElementById("p1");
    var oDiv = document.getElementById("div1");
    

    2. 获取选中文字

    知识点:

    1. document.selection.createRange().text
    2. window.getSelection().toString()

    这里,IE浏览器和其他浏览器又有差异了。所以编写一个封装函数:

    function selectText(){
    
            if(document.selection){  //IE
                return document.selection.createRange().text;
            }else{          //标准
                return window.getSelection().toString();
            }
    
    }
    

    3. 获取鼠标落点位置,显示分享图标

    知识点:

    1. onmouseup
    2. window.event
    3. clientX / clientY

    当选中文字数大于10时,才能分享。

    oP.onmouseup = function(ev){
    
            var ev = ev || window.event;
            var left = ev.clientX;
            var top = ev.clientY;
            if(selectText().length > 10){
    
                oDiv.style.display = "block";
                oDiv.style.left = left + "px";
                oDiv.style.top = top + "px";
    
            }else{
                oDiv.style.display = "none";
            }
    }
    

    4. 点击屏幕其他地方使分享图标消失

    知识点: cancelBubble

    通过 document.onclick 设置鼠标点击来消失分享按钮,会因为冒泡,而导致点击分享按钮也会消失。因为分享按钮本身也是document中的元素。

    
    所以需要阻止冒泡。
    oP.onclick = function(ev){
    
            var ev = ev || window.event;
            ev.cancelBubble = true;
    }
    
    document.onclick = function(){
            oDiv.style.display = "none";
    }
    

    5. 设置分享按钮的跳转功能

    其中的 http://service.weibo.com/share/share.php?searchPic=false&title=只针对谷歌浏览器。其他浏览器的会不同。。

    oDiv.onclick = function(){
    
        window.location.href = 'http://service.weibo.com/share/share.php?searchPic=false&title='
    +selectText()+
    '&url=http://blog.sina.com.cn/s/blog_4e1dad610102wrw7.html';
    }
    

    效果如图:

    分享界面

    选中文字-分享效果结束

    不积跬步无以至千里

    相关文章

      网友评论

          本文标题:选中文字-分享效果

          本文链接:https://www.haomeiwen.com/subject/cxyusttx.html