I am attempting a mobile first approach to site design. As part of this, I am using a media query to detect screen width over 768px
@media only screen and (min-width: 768px)
This triggers an image to be loaded through the CSS
h1:before{content: url(../static/logo.png)" ";}
Now, when this image loads, I would like to make it a hyperlink as well. As I am already using jquery elsewhere, I think the easiest thing to do would be to select the image in the DOM and add an hyperlink 开发者_开发百科element to the object. However, it looks to me like the image does not appear in the DOM because I use CSS to load the image (I'm unsure if the fact it is a pseudo-element makes a difference).
What is an effective strategy for loading objects (images) and applying markup to them in a mobile-first strategy? Thanks!
Just use jQuery to insert the image and the link into the DOM.
if ($(window).width() > 768) {
$('h1').before('<a href="#"><img src="images/logo.jpg" /></a>');
}
You cannot select or manipulate pseudo elements added with :before
or :after
. They simply don't appear in the DOM. From the Generated content spec:
Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).
See this example at jsFiddle.
Using jQuery to add the image and the link -- like in Rusty Jeans' answer -- is one good way to go.
If you are concerned about resizes, The most that the CSS approach would buy you is that the image would show/hide even if JS was disabled. In order to "linkify" it, you will need to monitor the resize
event, irregardless. (If resizing is really such a big issue for some reason.)
If it was me, I'd use real HTML -- an image, prelinked -- instead of pseudo elements. Use the media-query driven CSS to show or hide these nodes entirely (display:none
, etc.).
Another approach is to add the image via CSS, so that JS-disabled browsers would work after a fashion. BUT, then use JS to remove that CSS, pseudo element and to add a real element, with link, instead. That is, the "progressive-enhancement" approach.
:before
and :after
content is for presentational purposes, not structural, functional elements.
精彩评论