[英]How can I find the background image of a clicked element (or the nearest child or parent element that has a background image) using JavaScript?
I'm writing a Chrome extension that I want to use to provide the user with the URL of a background image using Chrome's right-click context menu. 我正在编写一个Chrome扩展程序,该程序可用于使用Chrome的右键单击上下文菜单为用户提供背景图片的URL。
Right now my problem is finding the background image. 现在我的问题是找到背景图像。 If a user right-clicks the correct element then it's easy.
如果用户右键单击正确的元素,那么这很容易。 But if they click a child of that element then I have to look at the parents.
但是,如果他们单击该元素的一个孩子,那么我必须看看父母。 What's the most efficient way to handle this?
处理此问题的最有效方法是什么?
Some notes: I'm not injecting jQuery with my extension. 一些注意事项:我没有使用扩展名注入jQuery。 And I've also thought of the scenario where an element that is absolutely positioned above the desired background image would get in the way.
而且我还想到了这样一种情况,即绝对位于所需背景图像上方的元素会挡住。 But I'm not concerned with that at the moment.
但是我现在不关心这个。
Here is my code so far. 到目前为止,这是我的代码。 It works as long as the clicked element has a
background-image
. 只要clicked元素具有
background-image
它就可以工作。 Failing to find one, it does not look at the parents yet. 没有找到一个,它还没有看着父母。
document.body.addEventListener('contextmenu', function(ev) {
// get computed style
var style = window.getComputedStyle(ev.target, false);
// img src is inside 'url(' + ')' - slice those off
var src = style.backgroundImage.slice(4, -1);
console.log(src);
return false;
}, false);
function getBackgroundImage(el) { if (el == null) { return null; } var backgroundImage = window.getComputedStyle(el, false).getPropertyValue("background-image"); if (backgroundImage !== 'none') { return backgroundImage.slice(4, -1); } else { return getBackgroundImage(el.parentElement); } } document.body.addEventListener('contextmenu', function(ev) { var src = getBackgroundImage(ev.target); console.log(src); }, false);
.grand-child { height: 100px; width: 100px; background: green; } .parent { background: url('http://google.com'); }
<div class="parent"> <div class="child"> <div class="grand-child"> </div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.