JS动画及获取文字

JS动画及获取文字

一、获取选中的文字

使用window.getSelection().toString()方法来获取选中的文字,在选中文字鼠标松开后会获取到选中的文字:

        <p>可以选中一些文本</p>
		
		<script type="text/javascript">
			let selected = window.getSelection().toString();
			console.log(selected);
			if(selected != '' && selected != null){
				window.alert('要百度搜索吗?');
			}
		</script>

二、让内容可编辑

  • 第一步:为元素设置contenteditable属性并赋值为true,让元素具有可编辑功能,当将其值赋值为false时不可编辑;

  • 第二步:伪元素设置spellcheck属性,并赋值为true,即开启拼写检查,设置值为false时关闭拼写检查

**注意:**浏览器定义了多文本编辑命令,使用dicument,execCommand()可以调用(比如copy,selectAll等命令;在使用execCommand()方法时,界面元素的contenteditable属性值不能设置为true,否则会影响copy命令)

        <div contenteditable="true" spellcheck="true"></div>
		<button>提交</button>
		<script type="text/javascript">
			let div = document.querySelector('div');
			let btn = document.querySelector('button');
			 btn.onclick = function(){
				 console.log(div.innerText);
			 }
		</script>

三、JS动画

原理:通过定时器setInterval()不断移动盒子位置。

例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box1{
				width: 200px;
				height: 200px;
				position: absolute;
				top: 50px;
				background-color: #3B78DD;
			}
			.box2{
				width: 100px;
				height: 100px;
				position: absolute;
				top: 400px;
				background-color: lightblue;
			}
			button{
				position: absolute;
				top: 300px;
			}
		</style>
	</head>
	<body>
		
		<div class="box1"></div>
		<div class="box2"></div>
		<button>点击移动box2</button>
		
		<script type="text/javascript">
			let box1 = document.querySelector('.box1');
			let box2 = document.querySelector('.box2');
			let btn = document.querySelector('button');
			
			function animate(obj, disdance, speed){
				clearInterval(obj.timer);
				obj.timer = setInterval(function(){
				    let moving = obj.offsetLeft;
					moving += 1;
					obj.style.left = moving + 'px';
					if(moving > disdance){
						clearInterval(obj.timer);
					}
				},speed);
			}
			
			animate(box1,300,5);
			
			btn.onclick = function(){
				animate(box2,400,3);
			}
			
		</script>
		
	</body>
</html>

你可能感兴趣的:(JS动画及获取文字)