问题
I am developing a site where I want to access a menu display property. If the menu is closed (display: none) then I want to open it, if it's open (display: block) then I want to close it.
I define the menu as closed in responsive media query (if width is higher then menu is always visible with !important in media query), the rest I control in Javascript:
var attach_menu_control = function() {
var $sidebar = document.querySelector('.sidebar')
var $sidebar_content = document.querySelector('.sidebar .content')
var $menu_opener = document.querySelector('.sidebar .menu-closed')
var hide_menu = function() {
console.log('Hide menu is run.')
$sidebar_content.style.display = 'none'
$menu_opener.style.display = 'block'
$sidebar.style.width = '40px'
}
var show_menu = function() {
console.log('Show menu is run.')
$sidebar_content.style.display = 'block'
$menu_opener.style.display = 'none'
$sidebar.style.width = '270px'
}
var click_handler = function(e){
console.log('Click handler is run.')
debugger
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if ($sidebar_content.style.display == 'none') { // Here it is `""` instead of `none`
show_menu()
} else if (width <= 724) {
hide_menu()
}
}
var $main = document.querySelector('main')
$main.addEventListener('click', hide_menu)
$sidebar.addEventListener('click', click_handler)
var event = new Event('click');
$sidebar.dispatchEvent(event)
}
Problem is, the first time this is run - the $sidebar_content.style.display is an empty string "" even though if I check it is definitely display: none in media query:
@media only screen and (max-width: 724px) {
/* Force sideback to be in closed mode when new page is opened */
.sidebar {
width: 40px;
}
.sidebar .content {
display: none;
}
}
Where can I get the values defined by media queries in Javascript? I don't want to access the rules themselves, I just want to know what's the current set value..
The site is here: www.saulesinterjerai.lt
回答1:
If I understand the original question correctly, then the desire is to be able to read the current CSS values once @media settings have been taken into account.
I believe that the following should suffice as it reads out the current rendered state of the element.
window.getComputedStyle($sidebar_content)
Important note - In modern browsers, there can be a delay between setting a style or class, and the re-flow of the page. It may therefore be necessary to set a timeout and read the computed value after a short pause. YMMV.
来源:https://stackoverflow.com/questions/44736557/how-to-get-current-css-value-defined-by-media-query-in-javascript