css实现鼠标选中文字后改变背景色的方法

css实现鼠标选中文字后改变背景色的方法

小编给大家分享一下css实现鼠标选中文字后改变背景色的方法,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

css中可以使用“::selection”选择器来实现鼠标选中文字后改变背景色,只需给文字元素E添加“E::selection{background: 背景色值;}”即可。

css实现鼠标选中文字后改变背景色

css鼠标选中文字后改变背景色可以使用::selection选择器。

::selection选择器匹配元素中被用户选中或处于高亮状态的部分。::selection只可以应用于少数的CSS属性:color、background、cursor和outline。

代码示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<style type="text/css">
			p {
				border: 1px solid red;
			}
			
			.color::-moz-selection {
				background: #93c;
				color: #fcf;
			}
			
			.color::selection {
				background: #93c;
				color: #fcf;
			}
		</style>
	</head>

	<body>
		<p>默认文本。测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!</p>
		<p class="color">鼠标选中文字后改变背景色。测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!</p>
	</body>

</html>

效果图:

css实现鼠标选中文字后改变背景色的方法

看完了这篇文章,相信你对“css实现鼠标选中文字后改变背景色的方法”有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!