更改标题样式在Chrome

时间:2016-04-23 08:06:56

标签: javascript google-chrome

我试图改变我的h1的外观。我已经完成了部分代码,但我注意到它在Chrome中不起作用。谁知道为什么?如果你有一个建议如何更好地编写下面的代码:

链接:http://codepen.io/Winterfox/pen/KzRbpZ

window.onload = function() {

var ownHeading = document.getElementById("heading");
var newHeading = document.getElementById("newheading");

ownHeading.addEventListener("input", buildLayout);

function buildLayout() {
   newHeading.innerHTML = ownHeading.value;
};

/*---------------------------------------------------------*/

var changeStyleBtn = document.getElementsByClassName("changestyle-btn");
 var changeStyleUl = document.getElementById('change-h-font');

for (var i = 0; i < changeStyleBtn.length; i++) {
    changeStyleBtn[i].addEventListener('click', changeStyle, false);
}

function changeStyle() {

  changeStyleUl.style.display = "block";
};

/*-------------------------------------------------------*/

var changeStyleLi = changeStyleUl.getElementsByTagName('li');

for (var i = 0; i < changeStyleLi.length; i++) {
    changeStyleLi[i].addEventListener('click', changeFont, false);
 }

function changeFont() {
  // here it stops working in chrome (can't click on lis)
  alert("clic");
  console.log(this);
};

};

1 个答案:

答案 0 :(得分:1)

问题似乎是嵌入了ul元素#changestyle-btn div

<div class="changestyle-btn">+
    <ul class="changestyle" id="change-h-font">
        <li>1</li>
        <li>2</li>
    </ul>
</div>

将元素移出div后,它在Chrome中运行良好。

<div class="changestyle-btn">+</div>
<ul class="changestyle" id="change-h-font">
    <li>1</li>
    <li>2</li>
</ul>

这很可能是因为您已经将点击事件绑定到#changestyle-btn div,因此当您尝试点击li元素时,它只会触发第一个事件。