猿问

用JS生成的标签和原生标签 相同的CSS选择结果不同?

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title></title>

<style>

#ul{ width:50%;}

li{ background:#f5f5f5; border-bottom:1px solid #ddd; padding:5px 0; }

#ul li:nth-child(n+5){ background:#F90}

</style>

</head>

<body>

<ul id='ul'>

    <li>1</li>

    <li>2</li>

    <li>3</li>

    <li>4</li>

    <li>5</li>

    <li>6</li>

    <li>7</li>

    <li>8</li>

    <li>9</li>

    <li>10</li>

    <li>11</li>

    <li>12</li>

</ul>

</body>

</html>

以上代码是从第四个子元素开始选择


<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title></title>

<style>

#ul{ width:50%;}

li{ background:#f5f5f5; border-bottom:1px solid #ddd; padding:5px 0; }

#ul li:nth-child(n+5){ background:#F90}

</style>

</head>

<body>

<ul id='ul'>

<script>

for(var i=1;i<=12;i++){

    document.write('<li>' + i + '</li>')

}

</script>

</ul>

</body>

</html>

以上代码是从第三个子元素开始选择


请问这是为什么???


幕布斯6054654
浏览 543回答 3
3回答

潇潇雨雨

有两种解决方法第一:如果HTML和JS不变的话,可以把CSS选择器nth-child换成nth-of-type!<!doctype html><html><head><meta charset="utf-8"><title>选择某个区间的元素-CSS3</title><style>#ul{ width:50%;}li{ background:#f5f5f5; border-bottom:1px solid #ddd; padding:5px 0; }#ul li:nth-of-type(n+5){ background:#F90}/*ul li:nth-child(-n+2){ background:#ccc}*/</style></head><body><ul id='ul'><script>for(var i=1;i<=12;i++){&nbsp; &nbsp; document.write('<li>' + i + '</li>')}</script><!--&nbsp; &nbsp; <li>1</li>&nbsp; &nbsp; <li>2</li>&nbsp; &nbsp; <li>3</li>&nbsp; &nbsp; <li>4</li>&nbsp; &nbsp; <li>5</li>&nbsp; &nbsp; <li>6</li>&nbsp; &nbsp; <li>7</li>&nbsp; &nbsp; <li>8</li>&nbsp; &nbsp; <li>9</li>&nbsp; &nbsp; <li>10</li>&nbsp; &nbsp; <li>11</li>&nbsp; &nbsp; <li>12</li>-->&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</ul></body></html>第二种解决方法,CSS不变,就是照DriftKing说的把JS写在父元素外面,add进去:<!doctype html><html><head><meta charset="utf-8"><title>选择某个区间的元素-CSS3</title><style>#ul{ width:50%;}li{ background:#f5f5f5; border-bottom:1px solid #ddd; padding:5px 0; }#ul li:nth-child(n+5){ background:#F90}/*ul li:nth-child(-n+2){ background:#ccc}*/</style></head><body><ul id='ul'><!--&nbsp; &nbsp; <li>1</li>&nbsp; &nbsp; <li>2</li>&nbsp; &nbsp; <li>3</li>&nbsp; &nbsp; <li>4</li>&nbsp; &nbsp; <li>5</li>&nbsp; &nbsp; <li>6</li>&nbsp; &nbsp; <li>7</li>&nbsp; &nbsp; <li>8</li>&nbsp; &nbsp; <li>9</li>&nbsp; &nbsp; <li>10</li>&nbsp; &nbsp; <li>11</li>&nbsp; &nbsp; <li>12</li>-->&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</ul><script>var u = document.getElementById("ul");&nbsp;for(var i=1;i<=12;i++){&nbsp; &nbsp; var li = document.createElement("li");&nbsp;&nbsp; &nbsp; li.innerText = i;&nbsp; &nbsp; u.appendChild(li);&nbsp;}</script></body></html>

慕侠2389804

用js生成的标签,查看控制台可以看到这样的结构:可以看到ul下面有你的<script></script>同样,原生的标签中如果加入一个空的<script></script>空标签的话,两种方式的结果就一样了,感觉是把scritp标签页当成了ul的一个child.

富国沪深

你这个js的写法就有问题呀,页面加载完,直接append进去呀,写在html里,选择器肯定把他当成了一个子标签
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答