首页 > 解决方案 > 未选择文件时如何使按钮变灰

问题描述

当未选择要上传的文件时,我已经设法禁用该按钮,但我想更改它在禁用/启用时的外观(btn-secondary,btn-primary)

我试图更改 .css 文件,但它对我不起作用

当没有像这里这样选择文件时,我只希望按钮为灰色:https : //getbootstrap.com/docs/4.0/components/buttons/btn-scondary

$(document).ready(function() {
  $('input:file').change(function() {
    if ($(this).val()) {
      $('input:submit').attr('disabled', false);
    }
  });
});
.disabled {
  color: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td width="30%">
  <input type="file" name="file" id="profile-img" />
</td>
<td width="30%" align="left">
  <input type="submit" name="upload" class="btn btn-primary" value="Upload" disabled>
</td>

标签: jquerycss

解决方案


[attr]在 css中使用按属性选择 DOM

$(document).ready(
    function(){
        $('input:file').change(
            function(){
                if ($(this).val()) {
                    $('input:submit').attr('disabled',false);
                }
            }
        );
    });
input[disabled] {
    color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="file" id="profile-img"/>
<input type="submit" name="upload" class="btn btn-primary" value="Upload" disabled>

编辑您的评论

我尝试添加背景颜色:深灰色;但它没有用

因为您使用引导程序,所以您需要backround使用!important

$(document).ready(
  function() {
    $('input:file').change(
      function() {
        if ($(this).val()) {
          $('input:submit').attr('disabled', false);
        }
      }
    );
  });
input[disabled] {
  color: red;
  background: darkgray!important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<input type="file" name="file" id="profile-img" />
<input type="submit" name="upload" class="btn btn-primary" value="Upload" disabled>

或者

用起来!important 真的不是很好。所以你可以改变你的样式表链接的顺序

或设置一个特定 idinput并在 css 中使用它:

$(document).ready(function() {
  $('input:file').change(function() {
    if ($(this).val()) {
      $('input:submit').attr('disabled', false);
    }
  });
});
#btn-uplaod[disabled] {
  color: red;
  background: darkgray;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<input type="file" name="file" id="profile-img" />
<input type="submit" name="upload" class="btn btn-primary" id="btn-uplaod" value="Upload" disabled>


推荐阅读