[英]JQuery Highlight Inner Text of Div, OnClick
我正在尝试自动突出显示<pre>
的文本,以便更容易复制......以下是我一直在使用的内容:
jQuery( document ).ready( function() { $( 'pre' ).click( function() { $( this ).select(); var doc = document , text = $( this ) , range, selection; if( doc.body.createTextRange ) { range = document.body.createTextRange(); range.moveToElementText( text ); range.select(); } else if( window.getSelection ) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents( text ); selection.removeAllRanges(); selection.addRange( range ); } } ); } );
pre {cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre>This is Text</pre>
我搜索过的帖子都将“突出显示”称为背景颜色,但我想实际突出显示它,以便用户可以轻松复制。 如何修改上面的JS,以便当用户点击文本时突出显示它?
你的代码非常适合。 只需要进行一点改动。
text = $(this)
需要成为
text = this
您使用text
作为参数的函数是Vanilla JavaScript方法,因此期望DOM节点而不是jQuery对象。 在这种情况下,“这个”本身就是一个DOM节点。 但是,将它包装在$()中会将其转换为jQuery对象,然后由您稍后调用的函数无法使用。
jQuery( document ).ready( function() { $( 'pre' ).click( function() { $( this ).select(); var doc = document , text = this , range, selection; if( doc.body.createTextRange ) { range = document.body.createTextRange(); range.moveToElementText( text ); range.select(); } else if( window.getSelection ) { selection = window.getSelection(); range = document.createRange(); range.selectNodeContents( text ); selection.removeAllRanges(); selection.addRange( range ); } } ); } );
pre {cursor:pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre>This is Text</pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.