简体   繁体   中英

Check @media rule with javascript by detecting css rule

I know about matchMedia.js but I was thinking I could detect the current @media rule with something as easy as this. However, it's not working in firefox – (which usually means it's not correct in the first place...) Looking at it now, shouldn't the content be on an :after pseudo element? Any advice? I have a CodePen HERE:

CSS

#test {
  content:  "small"
}

@media only screen and (min-width: $bp1) {
  #test {
    content: "medium"
  }
}


jQuery

var sizeCheck = function() {

  if ( $("#test").css('content') === 'small') {

    $('.proof').text('jQuery knows this page is SMALL from reading the CSS @media rules.');

  } else if ( $("#test").css('content') === 'medium') {

    $('.proof').text('jQuery knows this page is MEDIUM from reading the CSS @media rules.');

  }

};

// run the function on document ready
$(document).ready(sizeCheck);

// AND run the function on window resize event
$(window).resize(sizeCheck);

You've got quite an interesting test there!

To answer your question: yes, content can only be used with :after and :before pseudo classes.

Applies to ::before and ::after pseudo-elements

Source: content - CSS | MDN

EDIT #1

I found something for you; looks like it is possible to get the content of :after 'after all' :)

var content = window.getComputedStyle(
    document.querySelector('#test'), ':after'
).getPropertyValue('content');

Source: Get Pseudo-Element Properties with JavaScript

I'm not used to CodePen, so created a jsfiddle .

EDIT #2

Looks like FireFox adds a double code to the actual value, so in the console it appeared like this: ""string"" .

A way around this could be to test against both like this:

if (content == '"small"' || content == 'small') {
    // ...
}

I updated the fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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