简体   繁体   English

使用href属性作为CSS背景图像

[英]Use `href` attribute as CSS background-image

I have the following HTML which I cannot modify. 我有以下无法修改的HTML。 There is a CSS file that I can. 我有一个CSS文件。 Is there a way to get the href value/attribute and use it as CSS background-image? 有没有一种方法来获取href值/属性并将其用作CSS背景图像?

I need something like: 我需要类似的东西:

    background-image: url(href value);

Is that possible? 那可能吗? The href value is the result of a search, so it's not always the same. href值是搜索的结果,因此并不总是相同。

<tr class="trdata1">
    <td class="file">
        <span class="nobr">
            <nobr>
                <a href="/C/.../.../image.jpg">
                    <img class="icon" src="/file.gif" alt="">$image.jpg
                </a>
            </nobr>
        </span>
    </td>
</tr>

No, there is no way to do it with pure CSS, you will have to use Javascript for that. 不,没有办法使用纯CSS做到这一点,您将必须使用Javascript。 Eg with jQuery: 例如,使用jQuery:

$('.your-element').css(
  'background-image', 'url(' + $('.trdata1 > .file a').attr('href') + ')'
);

You can get the attribute of that hyperlink, and apply it to the element with jquery. 您可以获取该超链接的属性,然后使用jquery将其应用于元素。

var imgHref = $(".nobr nobr a").attr("href");
$(".imageBg").css('background-image','url('+imgHref+')');

working example 工作实例

Note: Please ensure the class names are unique 注意:请确保班级名称是唯一的

There is no way to do it dynamically with pure CSS. 纯CSS无法动态地做到这一点。

In pure CSS you can do it only statically: 在纯CSS中,您只能静态执行此操作:

your-selector {
    background-image: url("static-value");
}

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

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