首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]css中字体不可选中

发布于 2024-11-11 19:20:44
0
27

CSS中的字体不可选中是指在网页中使用CSS样式表控制文字时,防止用户通过拖动或选择文字的方式来复制或修改网页中的内容。这种功能有时候在设计一些特定类型的网站时非常重要,例如在版权受保护的网站中。 b...

CSS中的字体不可选中是指在网页中使用CSS样式表控制文字时,防止用户通过拖动或选择文字的方式来复制或修改网页中的内容。这种功能有时候在设计一些特定类型的网站时非常重要,例如在版权受保护的网站中。

 body { 
       -webkit-user-select:none; 
       -moz-user-select:none;
       -ms-user-select:none;
        user-select:none; 
   } 

上面这段CSS代码是禁止选取字体的方法,它可以防止用户选择和复制位于网页中的文本,不过它并不是最常用的方法。

除了以上代码之外,还可以使用JavaScript创建相应的代码段实现字体不可选中的功能。这种方法需要使用JavaScript方法,可以通过以下代码实现:

 function disableSelection(target){
       if (typeof target.onselectstart!="undefined") // IE route
            target.onselectstart=function(){return false}
       else if (typeof target.style.MozUserSelect!="undefined") // Firefox route
            target.style.MozUserSelect="none"
       else // All other route (ie: Opera)
            target.onmousedown=function(){return false}
       target.style.cursor = "default";
   }
   
   // Every click on the page will enable selection
   function enableSelection(target){
       if (typeof target.onselectstart!="undefined")
            target.onselectstart=function(){return true}
       else if (typeof target.style.MozUserSelect!="undefined")
            target.style.MozUserSelect=""
       else
            target.onmousedown=function(){return true}
       target.style.cursor = "";
   }
   
   disableSelection(document.body); 

上面的代码使用JavaScript防止在鼠标单击页面时选择文本,并且当您单击页面时,会将选择重新启用。

总而言之,防止用户选择和复制位于网页中的文本是一种非常有用的方法。 通过使用CSS样式表或JavaScript创建相应的代码段,可以轻松地实现字体不可选中的功能。

评论
一个月内的热帖推荐
91云脑
Lv.1普通用户

62849

帖子

14

小组

291

积分

赞助商广告
站长交流