css选中文件后,如何更改表单中文件输入按钮的颜色?

问题描述

我正在制作一个简单的网页,其中包含输入类型文件的表单,我想在选择文件时更改“选择文件”按钮的边框颜色以指示选择了文件

我曾尝试在 css 中使用 :focus 伪类来尝试在按下时更改颜色,但这仅在单击页面上的其他内容时才有效。我也试过 :visited 伪类,但什么也没发生。

这是相关的HTML代码

<input type="file" id="file-input"></input>
<label for="file-input" class="file-button">Select File</label>

CSS:

.file-button {
    display: block;
    margin: 10px auto;
    width: 400px;
    border-radius: 10px;
    text-align: center;
    justify-content: center;
    color: black;
    font-weight: bold;
    font-size: 36pt;
    border: 5px solid grey;
    padding:8px 0px;

}

input[type="file"]{
    opacity: 0;
    width: 0.1px;
    height: 0.1px;
    overflow: hidden;
    z-index: -1;
    position: absolute;

}

input[type="file"]:focus+label {
    border-color: black;  
}

解决方法

有几种方法可以做到这一点。如果您有完整的 js 代码,那么回答起来会容易得多。 基本上,您可以使用三元来确定文件是否已上传(存储在状态中),然后基于此更改 css。

例如:

const [isUploaded,setIsUploaded] = useState(null)

//Change the upload to true once a file is selected

<label for="file-input" class={isUploaded ? "file-button-after-upload" : "file-button-before-upload">Select File</label>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...