使用javascript从css中检索背景图像而不使用它's的ID

retrieve background image from css using javascript without using it's ID

本文关键字:ID css javascript 检索 图像 背景 使用      更新时间:2023-09-26

我环顾四周,很难找到一个能做我想做的事情的线程。就我而言,我甚至不知道这是否可能。我想做的是在点击时检索背景图像文件名(尤其是如果它是一个链接)。我有一个记录所有点击的脚本,但我最后需要的是存储在CSS文件中的背景图像名称(甚至可以使用名称的文件路径)。对于如何在不使用div或类的情况下实现这一点,有人有想法或解决方案吗?以下是我现在拥有的:

JavaScript&HTML

<script type="text/javascript">
var arrayWithElements = new Array(); //,replaytimer;
document.onclick = clickListener;
function clickListener(e)
{
var clickedElement=(window.event)
                    ? window.event.srcElement
                    : e.target,
    tags=document.getElementsByTagName(clickedElement.tagName);
for(var i=0;i<tags.length;++i)
{
  if(tags[i]==clickedElement)
  {
    if(clickedElement.tagName=="A")
    {
      arrayWithElements.push({tag:clickedElement.tagName,index:i});
      console.log(clickedElement.baseURI,clickedElement.href,clickedElement.innerText,document.location.href,document.images.href);
    }
    if(clickedElement.tagName=="IMG")
    {
      arrayWithElements.push({tag:clickedElement.tagName,index:i});
      console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
    }
    if(clickedElement.tagName=="DIV")
    {
      arrayWithElements.push({tag:clickedElement.tagName,index:i});
      console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
    }
    if(clickedElement.tagName=="CLASS")
    {
      arrayWithElements.push({tag:clickedElement.tagName,index:i});
      console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
        }
      }
    }
  }
</script>
</head>
<a id="1" href="#">trial1</a>
<a id="2" href="http://www.google.com" target="blank">google</a>
<a id="3" href="http://www.google.com">google</a>
<a id="4" href="http://www.google.com" target="_blank"><img id="image" src="untitled.jpg"/></a>
<a id="5" href="trial.html">
<input type="text" id="text-test"/>
<a href="http://www.google.com"><div id="image-link"></div></a>

CSS:

#image-link {
        background-image:url('untitled.jpg');
        width: 50px;
        height:50px;
        border: 1px solid #000000;
}

这是一个测试文件,将在不久的将来转换使用。感谢

在较新的浏览器上,可以使用window.getComputedStyle(clickedElement)查找背景图像属性。

根据您的代码,在所有浏览器中只需使用JQuery的文件名或路径:

var withId = $("#image-link").css("background-image").split('(')[1].split(')'),
    withoutId = $("img").attr("src");
    // with id and css file
    console.log(withId[0]);
    // without id and inline style
    console.log(withoutId);

是的,正如Alnitak所说,使用getComputedStyle,但为了与更多浏览器兼容,请查看另一个问题:

获取元素CSS属性(宽度/高度)的设置值(以百分比/em/px/etc为单位)


注意:我希望能够评论另一个用户的好答案,而不是发布我自己的答案,这几乎是一样的,但有一些额外的信息。不幸的是,我不能,因为stackoverflow不允许代表少于50的用户这样做。所以我不得不这样发布