简体   繁体   English

如何使带有背景图像的div可选?

[英]How to make div with background-image selectable?

I have an image in my page and it's loaded as background of a div. 我的页面中有一张图片,它已作为div的背景加载。 I want this div to communicate with user as if it was an <img scr="..." with. 我希望该div与用户进行交流,就好像它是<img scr="..." How do I make this div selectable? 如何使该div可选? User can easily select img but not div w/o content. 用户可以轻松选择img但不能选择没有内容的div I tried different values of user-selectable but it seems it doesn't div in any way. 我尝试了不同的user-selectable值,但它似乎没有以任何方式div。

Disclaimer: I can't use <img src=""/> because my image url is located in css file. 免责声明:我不能使用<img src=""/>因为我的图像网址位于css文件中。 I can't use img tag with content css property because it doesn't work as expected in some browsers. 我不能将img标签与content CSS属性一起使用,因为它在某些浏览器中无法正常工作。

 div { background: url("https://static.pychat.org/images/dark_wall.png") no-repeat 0 0; width: 50px; height: 50px; margin:100px; } 
 this text is selectable but image below is not. Click run snippet to see it yourself. <div></div> 

Because you are using a <div> element to render your image, selecting it simply isn't possible in the way you are describing. 因为您使用的是<div>元素来渲染图像,所以按照描述的方式完全不可能选择它。 You can, however, use the URL located in your CSS file in an <img> tag via the src attribute as done in the following snippet: 但是,您可以通过src属性使用<img>标记中CSS文件中的URL,如以下代码片段所示:

 img { width: 50px; height: 50px; margin:100px; } 
 By using an img tag, the image is selectable. <img src="https://static.pychat.org/images/dark_wall.png"> 

This produces the exact same results, though the image is also selectable by the user. 尽管用户也可以选择图像,但这会产生完全相同的结果。 Using an image instead of a <div> tag would be a better choice in countless ways including web accessibility (a screen reader would have a very difficult time comprehending the empty div element). 使用图像代替<div>标签将是无数种更好的选择,包括Web可访问性(屏幕阅读器将很难理解空的div元素)。

That being said, if it truly is necessary that you use an empty, block-level element (though I wouldn't recommend it), there is a workaround. 话虽如此,如果确实有必要使用一个空的,块级的元素(尽管我不推荐使用),则有一种解决方法。 If you were to place the HTML entity &nbsp; 如果您要放置HTML实体&nbsp; (a single space) in your div element, the space would make it selectable in some sense. (单个空格)在div元素中,该空格会使它在某种意义上是可选的。 Using the space character, you can also prevent browsers from not rendering the element. 使用空格字符,还可以防止浏览器不渲染元素。 Note that this may not provide the intended results as only the space will be selected. 请注意,这可能无法提供预期的结果,因为只会选择空格。

 div { background: url("https://static.pychat.org/images/dark_wall.png") no-repeat 0 0; width: 50px; height: 50px; margin:100px; } 
 Your div element <div> &nbsp; </div> 

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

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