<div id="box">
<p class="b">item 1</p>
<p class="b">item 2</p>
<p class="b">item 3</p>
<p class="b">item 4</p>
<p class="b">item 5</p>
</div>
单击后如何加粗所选段落? 例如,如果我点击“第2项”,则在点击
后,只有第2项会以粗体显示答案 0 :(得分:3)
我建议:
function makeBold(el) {
el.style.fontWeight = 'bold';
}
var paragraphs = document.getElementsByTagName('p');
for (var i = 0, len = paragraphs.length; i<len; i++){
paragraphs[i].onclick = function(){
makeBold(this);
};
}
或者,如果您更愿意切换字体重量:
function toggleBold(el) {
el.style.fontWeight = el.style.fontWeight == 'bold' ? 'normal' : 'bold';
}
var paragraphs = document.getElementsByTagName('p');
for (var i = 0, len = paragraphs.length; i<len; i++){
paragraphs[i].onclick = function(){
toggleBold(this);
};
}
或者,如果您希望只有一个段落以粗体文本显示(单击第二个段落会将其他p
元素返回到非粗体状态):
function toggleBold(el) {
var siblings = el.parentNode.getElementsByTagName('p');
for (var i = 0, len = siblings.length; i<len; i++){
if (siblings[i] == el){
el.style.fontWeight = el.style.fontWeight == 'bold' ? 'normal' : 'bold';
}
else {
siblings[i].style.fontWeight = 'normal';
}
}
}
var paragraphs = document.getElementsByTagName('p');
for (var i = 0, len = paragraphs.length; i<len; i++){
paragraphs[i].onclick = function(){
toggleBold(this);
};
}
答案 1 :(得分:1)
试试这个:
<强> HTML:强>
<p class="b" onclick="GetBold(this)">item 2</p>
<强> JavaScript的:强>
function GetBold(current)
{
var array = document.getElementsByClassName('p');
for (var i = 0; i < array.length; i++)
{
array[i].style.fontWeight = 'normal';
}
current.style.fontWeight = 'bold';
}
答案 2 :(得分:0)
使用jQuery:
$('.b').click(function(){
$(this).css({'font-weight':'bold'})
})