<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 会加粗
<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 会加粗
我建议:
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);
};
}
尝试这个:
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';
}
使用 jQuery:
$('.b').click(function(){
$(this).css({'font-weight':'bold'})
})