Menu Home

跨浏览器实现复制URL至剪贴板

每天大家都在说搜索引擎优化,说网站推广,但是对于导入至站点的流量如何进一步保持用户的粘性,人性化的的页面设置,方便醒目的功能设置,等所有这些提高用户体验的贴心设置对于站点的贡献是无法量化说明的。

今天我要介绍的就是本站的用户体验优化的一个小细节-文章内添加复制本篇文章URL至剪贴板。

  • 最简单的方式,适用IE浏览器
  • <script language="javascript">
    	function copyToClipboard(txt) {
    		if(window.clipboardData) {
    			window.clipboardData.clearData();
    			window.clipboardData.setData(”Text”, txt);
    		}
    	}
    </script>
    <input type="button" value="复制本文URL至剪贴板" onClick="copyToClipboard('<?php the_permalink(); ?>')" />

  • 适用于 firefox 浏览器的方案
  • <script language="javascript">
    	function copyToClipboard(txt) {
    		if (window.netscape) {
    			try {
    				netscape.security.PrivilegeManager.enablePrivilege(”UniversalXPConnect”);
    			}
    			catch (e) {
    				alert(”您的firefox安全限制限制您进行剪贴板操作,请打开’about:config’将signed.applets.codebase_principal_support’设置为true’之后重试”);
    				return false;
    			}
    			var clip = Components.classes[’@mozilla.org/widget/clipboard;1′].createInstance(Components.interfaces.nsIClipboard);
    			if (!clip)
    				return;
    			var trans = Components.classes[’@mozilla.org/widget/transferable;1′].createInstance(Components.interfaces.nsITransferable);
    			if (!trans)
    				return;
    			trans.addDataFlavor(’text/unicode’);
    			var str = new Object();
    			var len = new Object();
    			var str = Components.classes[”@mozilla.org/supports-string;1″].createInstance(Components.interfaces.nsISupportsString);
    			var copytext = txt;
    			str.data = copytext;
    			trans.setTransferData(”text/unicode”,str,copytext.length*2);
    			var clipid = Components.interfaces.nsIClipboard;
    			if (!clip)
    				return false;
    			clip.setData(trans,null,clipid.kGlobalClipboard);
    		}
    	}
    </script>
    <input type="button" value="复制本文URL至剪贴板" onClick="copyToClipboard('<?php the_permalink(); ?>')" />
  • 以上两种方法能够实现绝大部分的用户需求,但是对于一些新型浏览器并不能支持。
    终极的解决方案是,使用jhuckaby写的Zero Clipboard的js类库。此方法利用 Flash完成进行复制内容到剪贴板,所以只要浏览器装有 Flash 就可以复制内容。
    下面介绍下本站实现复制本文链接至剪贴板的方法
  • 下载 Zero Clipboard 类库上传 Zero Clipboard 目录至站点
    zero clipboard
    比如本站上传至

    /public_html/wp-includes/js/

    对应的类库引用位置是

    https://www.track2web.com/wp-includes/js/zeroclipboard/ZeroClipboard.js

    添加以下代码至模板文件 single.php 相应位置,实现复制URL至剪贴板

    <!-- 引入 Zero Clipboard 类库 -->
    <script src="https://www.track2web.com/wp-includes/js/zeroclipboard/ZeroClipboard.js" type="text/javascript"></script>
    <script language="javascript">
    	function copyToClipboard(txt) {
    		//引入 Zero Clipboard flash文件
    		ZeroClipboard.setMoviePath( "https://www.track2web.com/wp-includes/js/zeroclipboard/ZeroClipboard.swf" );
    		//新建对象
    		clip = new ZeroClipboard.Client();
    		//设置指向光标为手型
    		clip.setHandCursor( true );
    		//通过传入的参数设置剪贴板内容
    		clip.setText(txt);
    		//添加监听器,完成点击复制后弹出警告
    		clip.addEventListener("complete", function (client, text) {
    			alert("您复制了本文URL地址为:\n" + text );
    		});
    		//绑定触发对象按钮ID
    		clip.glue("b_clip_button");
    	}
    </script>
    <!--页面添加按钮 注意 ID与注册的名称相同 触发事件为 onmouseover 传递 wordpress 固定链接 参数作为复制参数 -->
    <input id="b_clip_button" onmouseover="copyToClipboard('<?php the_permalink(); ?>')" type="button" value="复制本文URL地址至剪贴板" />

要点讲解:为什么使用 onmouseover 事件而不是 onclick 事件
定义的函数中的 clip 对象在页面载入的时候并不会建立,减轻页面负担。当用户需要进行复制操作的时候鼠标移到 按钮 上,触发 onmouseover 事件,因为 falsh 10 规定必须有点击事件才能够触发 falsh 动过。所以当用户点击按钮后才能实现复制操作
如果 按钮使用 onclick 事件,当用户点击按钮时,将仅仅新建了 clip 对象,并没有能够完成 falsh 的复制动作,必须再点击一次按钮才能实现复制,而使用 onmouseover 事件则避免了两次点击的问题。

Categories: 用户体验

Tagged as:

RoyAkon

732 replies

  1. What’s up it’s me, I am also visiting this web page daily, this site is truly pleasant and the people are truly sharing pleasant thoughts.

  2. My spouse and I stumbled over here coming from a different web page and thought I should check things out.
    I like what I see so now i am following you. Look forward to looking over your web page
    repeatedly.

  3. Link exchange is nothing else but it is simply placing the other person’s website
    link on your page at proper place and other person will also do similar for
    you.

  4. Can I simply just say what a relief to find a person that actually knows what they are talking about over the internet.

    You certainly understand how to bring a problem to light and make
    it important. More and more people have to check this out and understand this side of your story.
    It’s surprising you are not more popular given that you certainly possess
    the gift.

  5. When someone writes an article he/she keeps the thought of a user
    in his/her mind that how a user can be aware of it. Thus that’s why this
    paragraph is perfect. Thanks!

  6. First off I want to say fantastic blog! I had a quick question which
    I’d like to ask if you don’t mind. I was curious to know how you center yourself and
    clear your head prior to writing. I have had a hard time clearing my thoughts in getting my thoughts
    out. I truly do enjoy writing however it just seems like the
    first 10 to 15 minutes are lost simply just trying to figure out how to
    begin. Any ideas or tips? Thank you!

  7. hello!,I like your writing very a lot! percentage we keep in touch extra about
    your article on AOL? I require a specialist in this area to
    solve my problem. Maybe that’s you! Looking ahead to peer you.

  8. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something.

    I think that you could do with some pics to drive the message home
    a little bit, but instead of that, this is wonderful blog.

    A great read. I’ll definitely be back.

  9. Today, I went to the beach front with my children. I found a sea
    shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and
    screamed. There was a hermit crab inside and it pinched
    her ear. She never wants to go back! LoL I know this
    is totally off topic but I had to tell someone!

  10. This is a verdy good tip particularly too thoze new too the blogosphere.
    Simple butt very precise information… Appreciate your sharing this one.
    A must read post!
    web site live bet betting match

  11. It’s remarkable to pay a quick visit this website and reading the
    views of all friends regarding this article, while I
    am also zealous of getting experience.

  12. Your doctor or dietician will help you to set sensible goals determined by an appropriate weight for your height, build and age.
    However, it may be perhaps the most common misunderstanding that taking lifelong medications or having major surgeries will be the solution for several chronic illnesses.
    These professionals will clean the filters and also the vents and replace any which need
    new attention.

  13. I blog often and I seriously appreciate your content. This great article
    has really peaked my interest. I am going to take a note
    of your blog and keep checking for new details about once per
    week. I opted in for your RSS feed as well.

  14. Nice post. I was checking constantly this weblog and I’m impressed!
    Very useful info specifically the last section 🙂 I care for such info much.
    I used to be looking for this particular information for a long time.
    Thank you and best of luck.

  15. Definitely consider that which you stated. Your favorite justification seemed to
    be on the internet the easiest thing to take note of.
    I say to you, I definitely get irked even as folks
    consider worries that they plainly don’t realize about.
    You managed to hit the nail upon the top as well as defined out the whole thing without
    having side-effects , other people could take a signal.
    Will probably be again to get more. Thanks

  16. Pretty section of content. I just stumbled upon your site and in accession capital to assert
    that I get in fact enjoyed account your blog posts.
    Anyway I will be subscribing to your feeds and even I achievement you access
    consistently quickly.

  17. Attractive section of content. I just stumbled upon your website and in accession capital to assert that I acquire
    in fact enjoyed account your blog posts. Anyway
    I will be subscribing to your feeds and even I achievement you
    access consistently fast.

  18. Hey There. I discovered your blog the use of msn.
    This is a very well written article. I will make sure to bookmark it and come back to read
    extra of your helpful info. Thanks for the post. I will definitely
    return.

  19. Hey I know this is off topic but I was wondering if you knew of any widgets
    I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time
    and was hoping maybe you would have some experience with something like this.

    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to
    your new updates.

  20. Nice post. I was checking continuously this blog
    and I’m impressed! Very helpful information specially the last part
    🙂 I care for such information much. I was looking for this certain info for a long time.
    Thank you and good luck.

  21. #Hookahmagic
    Мы всегда с Вами и стараемся нести только позитив и радость.
    Ищите Нас в соцсетях,подписывайтесь и будьте в курсе последних топовых событий.
    Строго 18+

    Какой кальян купить новичку?
    Если это первая покупка, то лучше начать с более простых моделей. Это изделия со средней высотой (70 см) и одной насадкой. Количество труб влияет на работу устройства. Это будет трудная задача.

    Очень важно обращать внимание на материал шахты. Чем он прочнее, тем дольше прибор прослужит. Срок службы устройства минимум на 10 лет.

    https://h-magic.su/pharaon
    Рекомендуется обращать внимание на внутренний диаметр шахты. Он должен быть минимум 12 см.

    Можно рассмотреть также электронные изделия. Они компактные и простые в использовании. Безопасный дым. Его можно курить (парить) даже в общественных местах. Что касается его вкусовых качеств – они ничем не уступают традиционным устройствам. Какой электронный кальян купить лучше? Самый распространенный гаджет – площадь Sturbuzz.

发表评论

电子邮件地址不会被公开。 必填项已用*标注