繁体   English   中英

背景图像样式在HTML标头中不起作用

[英]background-image style not working in HTML header

我试图在按下按钮时更改css类的“背景图像:”。

jQuery的:

$(function() {
    $('button').on('click', function() {
        $('.masthead2').css('background-image', 'url("../img/whiteheader.png")');
    });
});

CSS:

.masthead2 {
    position: relative;
    width: 100%;
    height: auto;
    min-height: 35rem;
    padding: 15rem 0;
    background-image: url("../img/roseheader.png");
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-size: cover;
}

当我按下按钮时,CSS样式中的“背景图像:”将被删除。 然后,HTML随之改变:

<header class="masthead2">

为此:

<header class="masthead2" style='background-image: url("../img/whiteheader.png");'

但是,在页面上; 完全不显示图像。 我尝试将网址直接复制到CSS中,并加载新图像。 因此,我相信网址是正确的。

如果直接在CSS中更改背景图片,则可以解决此问题。

图像的路径可能不正确。 如果它在css内,则该路径是相对于css文件的,但在html内并不表示相同的位置。 尝试图像的绝对路径。 例如

$(function() {
    $('button').on('click', function() {
        $('.masthead2').css('background-image', 'url("http://www.mywebsite.com/img/whiteheader.png")');
    });
});

我已经检查了完整的代码,它可以在我的终端运行,请检查您的图片网址(如果其中存在图片)。 这是代码:-

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Animation</title>
    <link rel="stylesheet" href="style.css" />
    <style>
        .masthead2 {
    position: relative;
    width: 100%;
    height: auto;
    min-height: 35rem;
    padding: 15rem 0;
    background-image: url("https://lh3.googleusercontent.com/proxy/ogwfaF0iwa05OnTNQFyD0rZ384sAN74p5xwJE6qfJmrEFcmgxlXo4zg22lrlaLcaS_hp9pFCu8s8QZ-GgDy37DxWVOHpq2B4IV35vb4wgHBWfJiYqI_AVARVMaguPane4Raedg=w530-h212-p-rw");
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-size: cover;
}
    </style>
</head>

<body>

  <header class="masthead2"></header>

<button>Submit</button>

</body>
<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>
<script>
    $(function() {
    $('button').on('click', function() {
        $('.masthead2').css('background-image', 'url("https://upload.wikimedia.org/wikipedia/en/thumb/6/63/IMG_%28business%29.svg/1200px-IMG_%28business%29.svg.png")');
    });
});
</script>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM