我目前正在使用一个在线文本编辑器作为项目的一部分,至少可以说,我的粗体按钮有一个小问题。
下面是我的HTML按钮:
<button id="b" onclick="bold()">Bold</button>
下面是我在JavaScript中的函数:
function bold() {
var ban = document.getElementById("b");
if (ban == true) {
document.getElementById("texto").style.fontWeight = 'bold';
} else {
document.getElementById("texto").style.fontWeight = 'normal';
}
}
如果我把所有东西都去掉,只留下:
function bold() {
document.getElementById("texto").style.fontWeight = 'bold';
}
它使我的文本加粗,但我的目标是当我再次单击该按钮时,能够取消我的<textarea>
中的文本加粗。
我做错了什么?
发布于 2016-11-12 05:11:20
function Bold()
{
var ban =document.getElementById("texto").style.fontWeight ;
if(ban == 'normal')
{
document.getElementById("texto").style.fontWeight = 'bold';
}
else
{
document.getElementById("texto").style.fontWeight = 'normal';
}
}
<button id="b" onclick="Bold()">Bold</button>
<p id="texto" style="font-weight:normal;">Hi</p>
发布于 2016-11-12 04:59:32
试试这个:
function Bold()
{
var text = document.getElementById("texto");
var weight = text.style.fontWeight;
if(weight == 'bold')
{
text.style.fontWeight = 'normal';
}
else
{
text.style.fontWeight = 'bold';
}
}
发布于 2016-11-12 05:06:33
使用外部JavaScript,这样它就会被缓存,这样加载速度就会更快,而且作为一种最佳实践,您应该将您的HTML从JavaScript中分离出来。但实际上,您的问题是每次调用函数时都要重新定义var ban
。观看并学习:
//<![CDATA[
// change the pre var on any page using this onload technique
var pre = onload, doc, bod, htm, E, boldToggle; // higher scope in case other onloads need access
onload = function(){ // same as window.onload - note that window is implicit
if(pre)pre(); // execute previous onload
doc = document, bod = doc.body, htm = doc.documentElement;
E = function(id){
return doc.getElementById(id);
}
boldToggle = (function(){ // Anonymous function executes and scopes off var b before returning an unexecuted function
var b = 0;
return function(e){ // e is for Element here - this is function that is returned unexecuted
var s = e.style;
if(b){ // test if bold
s.fontWeight = 'normal'; b = 0;
}
else{
s.fontWeight = 'bold'; b = 1;
}
}
})();
E('b').onclick = function(){
boldToggle(this); // this within Event refers to Element id='b' in this case
}
} // end onload
//]]>
哦,如果使用<button>
,那将是一个提交按钮,所以要这样做:
<button type='button' id='b'>Bold</button>
我更喜欢:
<input type='button' id='b' value='Bold' />
这一点更清楚,因为许多浏览器无法访问<button>
上的.innerHTML
,因为它实际上是一个输入,所以<button>
标记可能具有误导性。我在这里更正了一些代码时了解到了这一点,其中用户在<button>
中嵌套了其他元素。这在某些浏览器上是行不通的,所以我更喜欢<input type='button' />
。如果您曾经在大型项目中工作,这可以防止其他人尝试在其中抛出不属于其中的元素。
https://stackoverflow.com/questions/40559663
复制