单击后加粗段落

时间:2013-03-04 14:39:13

标签: javascript html css

<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项会以粗体显示

3 个答案:

答案 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);
    };
}

JS Fiddle demo

或者,如果您更愿意切换字体重量:

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);
    };
}

JS Fiddle demo

或者,如果您希望只有一个段落以粗体文本显示(单击第二个段落会将其他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);
    };
}

JS Fiddle demo

答案 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'})
})