uni-app中 div last-child选择器无法生效

uni-app中 div last-child选择器无法生效

项目名称 HbuilderX
PC开发环境操作系统 Windows
PC开发环境操作系统版本号 win10
HBuilderX版本号 3.1.9

操作步骤:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
{
margin: 0;
padding: 0;
}
    div:first-child {  
        width: 200px;  
        height: 200px;  
        background-color: yellow;  
    }  

    div:last-child {  
        width: 200px;  
        height: 200px;  
        background-color: red;  
    }
</style>
</head>
<body>
<div>1</div>
<div>2</div>
</body>
</html>

预期结果:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
{
margin: 0;
padding: 0;
}
    div:first-child {  
        width: 200px;  
        height: 200px;  
        background-color: yellow;  
    }  

    div:last-child {  
        width: 200px;  
        height: 200px;  
        background-color: red;  
    }
</style>
</head>
<body>
<div>1</div>
<div>2</div>
</body>
</html>

实际结果:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
{
margin: 0;
padding: 0;
}
    div:first-child {  
        width: 200px;  
        height: 200px;  
        background-color: yellow;  
    }  

    div:last-child {  
        width: 200px;  
        height: 200px;  
        background-color: red;  
    }
</style>
</head>
<body>
<div>1</div>
<div>2</div>
</body>
</html>

bug描述:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
{
margin: 0;
padding: 0;
}
    div:first-child {  
        width: 200px;  
        height: 200px;  
        background-color: yellow;  
    }  

    div:last-child {  
        width: 200px;  
        height: 200px;  
        background-color: red;  
    }
</style>
</head>
<body>
<div>1</div>
<div>2</div>
</body>
</html>
代码如上 第二个div用last-child不生效
我在浏览器调试了一下 删除了js代码就生效了
以下是截图


更多关于uni-app中 div last-child选择器无法生效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app中 div last-child选择器无法生效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中,:last-child选择器可能无法按预期工作,主要原因是uni-app在编译时会在页面根节点自动添加额外元素,导致DOM结构发生变化。

从截图可见,实际渲染的DOM中,<div>2</div>并非其父元素的最后一个子节点,后面还有uni-app自动添加的脚本元素,因此:last-child选择器无法匹配到目标div。

解决方案:

  1. 改用:last-of-type选择器:
div:last-of-type {
    width: 200px;
    height: 200px;
    background-color: red;
}
  1. 使用类选择器结合uni-app的数据绑定:
<template>
    <div :class="index === list.length - 1 ? 'last-item' : ''">内容</div>
</template>
  1. 使用结构伪类选择器组合:
div:nth-last-child(2) {
    width: 200px;
    height: 200px;
    background-color: red;
}
回到顶部