jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。取消文本选中是指阻止用户在网页上选中文本的操作。
取消文本选中的方法主要有两种:
user-select
来禁止文本选中。.unselectable {
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE/Edge */
user-select: none; /* Standard */
}
<div class="unselectable">
This text cannot be selected.
</div>
<div id="unselectable">
This text cannot be selected.
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#unselectable').on('mousedown', function(e) {
e.preventDefault();
});
});
</script>
原因:
user-select
属性已正确设置,并且没有拼写错误。解决方法:
$(document).ready()
方法。<div id="unselectable">
This text cannot be selected.
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#unselectable').css('user-select', 'none').on('mousedown', function(e) {
e.preventDefault();
});
});
</script>
通过以上方法,可以有效解决 jQuery 取消文本选中不起作用的问题。
领取专属 10元无门槛券
手把手带您无忧上云