js获取可视区域文字的方法

JavaScript013

js获取可视区域文字的方法,第1张

一、获取选中的文字

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

<p>可以选中一些文本</p>

<script type="text/javascript">

let selected = window.getSelection().toString()

console.log(selected)

if(selected != '' &&selected != null){

window.alert('要百度搜索吗?')

}

</script>

1

2

3

4

5

6

7

8

9

1

2

3

4

5

6

7

8

9

二、让内容可编辑

第一步:为元素设置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>

1

2

3

4

5

6

7

8

9

1

2

3

4

5

6

7

8

9

三、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>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

javascript中img.src属性可以获取到图片的完整路径, 相对路径要通过与相对位置计算得出。计算方法:

先要明确自己的相对位置在哪,这个是需要人为指定的。

核心代码如下:

var res=document.getElementById("img").src

var root_href='根目录路径'

res=document.getElementById("img").src.replace(root_href,'')

用jquery方法

var res=$("#img").attr("src")

res=res.substring(res.indexOf("根")+2)

更多关于在上传文件的过程得到完整路径的方法请参考如下:

file.select()

var res=document.selection.createRange().text

var res=file.files.item(0).getAsDataURL()

var res=file.value