小地方提高Theme评论框用户体验

> 我以前一直以为 JavaScript 是可以舍弃的技能,但是后来我不得不承认我错了。
> JavaScript 是不可或缺的东西,有非常重要,难以取代的地位。

> 我现在只是一个 JavaScript 初学者,那么我们初学者一起从各个细节入手。
> 开始学习 JavaScript,那么这次所要使用的功能是JavaScript的 focus(); 函数。

> P.s. 感谢Exia童鞋,我在犹豫该不拘小节还是该注重细节的时候,他告诉我,细节决定成败。

> 因为点击评论框右上角的回复之后,会自动在评论框中添加以下代码。

1
<a href="#comment-1672">@Awu</a>,<br />

> 但是在这里光标却出现在代码的左边,而我们要输入评论需要在下面多点一下鼠标,才能不破坏格式。
> 如果不点击鼠标,或者不按一下键盘下键,那么直接输入会出现一下情况,就Fail了。

1
Hello,World<a href="#comment-1672">@Awu</a>,<br />

> 所以我们就需要使用 Focus 函数来使结果变成这个样子。

1
2
<a href="#comment-1672">@Awu</a>,<br />
Hello,World

> Focus函数语法

1
focus();

> 示例

1
2
3
4
5
function setblur()
{
        dreamdutxt.focus();
        dreamdutxt.blur();
}
1
2
3
input type="button" value="获得焦点" onclick="javascript:dreamdutxt.focus()" />
<input type="button" value="失去焦点" onclick="setblur()" />
<input type="text" value="text" name="dreamdutxt" onblur="alert('dreamdutxt is onblur')" />

> 当点击获得焦点的时候,输入光标会处在 Dreamdutxt 输入框中。
> 那么点击失去焦点的时候,输入光标则会从 Dreamdutxt 输入框中消失。
> 好啦,理解了这个之后就可以对 ElegantBox 模板的 JavaScript 进行修改啦。

> 下面的内容是 ElegantBox 模板的 Comment.js 文件中的一个函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function appendReply(insertStr, commentBox) {
	if(document.getElementById(commentBox) &&
 document.getElementById(commentBox).type == 'textarea') {
		field = document.getElementById(commentBox);
	} else {
		alert("The comment box does not exist!");
		return false;
	}
 
	if (field.value.indexOf(insertStr) > -1) {
		alert("You've already appended this reply!");
		return false;
	}
 
	if (field.value.replace(/\s|\t|\n/g, "") == '') {
		field.value = insertStr;
	} else {
		field.value = field.value.replace(/[\n]*$/g, "") + '\n\n' + insertStr;
	}
	field.focus();
}

> 这一行是正确调用JS里面的回复函数之后才会执行的,这里把 CommentBox 定义为 field

1
field = document.getElementById(commentBox);

> 所以我们在下面第五行添加这个函数,就能使正确调用JS回复函数的时候,输入光标达到我们想要的位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function appendReply(insertStr, commentBox) {
	if(document.getElementById(commentBox) &&
 document.getElementById(commentBox).type == 'textarea') {
		field = document.getElementById(commentBox);
		field.focus();
	} else {
		alert("The comment box does not exist!");
		return false;
	}
 
	if (field.value.indexOf(insertStr) > -1) {
		alert("You've already appended this reply!");
		return false;
	}
 
	if (field.value.replace(/\s|\t|\n/g, "") == '') {
		field.value = insertStr;
	} else {
		field.value = field.value.replace(/[\n]*$/g, "") + '\n\n' + insertStr;
	}
	field.focus();
}
Leave a comment

28 Comments.

  1. Auston Jary 坐沙发!#1

    我来坐沙发~

  2. 第三眼 坐板凳!#2

    板凳,沙发上人太多,坐板凳看戏

  3. Awu 躺地板!#3

    你用的这个语法高亮是哪个的插件?

  4. 学习了

  5. 天缘博客 下水道!#5

    实际上就是光标定位,以前写过类似的,要注意浏览器之间的兼容性

  6. 这个真的是很细节的地方,我都没有注意到~

  7. 不错,就是代码太多头痛啊

  8. javascript没了他,网站就太傻了

  9. 一看到代码,小农夫就头痛呀

  10. 真的羡慕WP的用户有这么多贡献者

  11. ...看不太懂……不过还是支持下……

Leave a Reply

:evil: :razz: :wink: :rolleyes: :redface: :cry: :biggrin: :lol: :idea: :mrgreen: :mad: :exclaim: more »

[ Ctrl + Enter ]