-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsou.js
85 lines (75 loc) · 2.97 KB
/
sou.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
作者:D.Young
主页:https://yyv.me/
github:https://github.com/5iux/sou
日期:2020/11/18
重写: dwxh
日期: 2021年2月25日
版权所有,请勿删除
*/
document.addEventListener("DOMContentLoaded", function () {
let wid = document.body.offsetWidth;
if (wid > 640) {
document.getElementById("wd").focus();
}
document.getElementById("menu").addEventListener("click", function () {
toggleClass(this, 'on');
toggleClass(document.getElementById("list"), 'closed');
toggleClass(document.getElementById("wth"), 'hidden');
})
document.getElementById("content").addEventListener("click", function () {
removeClass(document.getElementById("menu"), 'on');
addClass(document.getElementById("list"), 'closed');
removeClass(document.getElementById("wth"), 'hidden');
document.getElementById("word").style.display = 'none';
})
document.getElementById("wd").addEventListener("keyup", function () {
let keywords = this.value;
if (keywords === '') {
document.getElementById("word").style.display = 'none';
} else {
let osc = document.createElement("script"); /*创建一个script标签*/
osc.src = "https://suggestion.baidu.com/su?cb=handleSuggestion&wd=" + keywords;
osc.id = "osc";
/*srcipt的src值引入百度的url,然后将otext文本框中输入的内容连接到url,在后面在运行自己的方法*/
document.body.appendChild(osc);
}
})
});
function handleSuggestion(data) {
let wordElement = document.getElementById("word");
while (wordElement.firstChild) wordElement.removeChild(wordElement.firstChild);
if (data.s.length === 0) {
wordElement.style.display = 'none';
} else {
wordElement.style.display = 'block';
data.s.forEach((item) => {
wordElement.insertAdjacentHTML('afterbegin', '<li class="select-items"><svg class="icon" style=" width: 15px; height: 15px; opacity: 0.5;" aria-hidden="true"><use xlink:href="#icon-search"></use></svg> ' + item + '</li>');
})
document.querySelector('#word li').addEventListener('click', function () {
document.getElementById("wd").value = this.innerText.trim();
document.getElementById('word').style.display = 'none';
document.querySelector('form').submit();
});
}
document.body.removeChild(document.getElementById("osc"))
}
function hasClass(obj, cls) {
return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(obj, cls) {
if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}
function removeClass(obj, cls) {
if (hasClass(obj, cls)) {
let reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
obj.className = obj.className.replace(reg, ' ');
}
}
function toggleClass(obj, cls) {
if (hasClass(obj, cls)) {
removeClass(obj, cls);
} else {
addClass(obj, cls);
}
}