[英]Jquery, Remove class when width screen is 1050px
這是我正在使用的JS代碼:
$("document").ready(function($){
var nav = $('#menu2');
$(window).scroll(function () {
if ($(this).scrollTop() > 90) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
但我似乎無法將其納入我的代碼中。
function checkWidth(init){
/*If browser resized, check width again */
if ($(window).width() < 514) {
$('html').addClass('mobile');
}
else {
if (!init) {
$('html').removeClass('mobile');
}}}$(document).ready(function() {
checkWidth(true);
$(window).resize(function() {
checkWidth(false);
});
我想要的是當.f-nav
添加到#menu2
,當屏幕<1050
,應刪除該類。
要將html
更改為#menu2
,只需將其替換為另一個。 在這方面,jQuery非常簡單
if ($(window).width() < 514) {
$('#menu2').addClass('f-nav');
} else {
$('#menu2').removeClass('f-nav');
}
這最好通過媒體查詢實現
@media screen and (max-width:1050px){
.mobile{
/* will only apply on devices narrower than 1050px */
}
}
編輯:也可以在現代瀏覽器中使用javascript進行媒體查詢
if (matchMedia) { // check if browser supports media queries from JavaScript
var mq = window.matchMedia("(max-width: 1050px)");
WidthChange(mq);
// every time width changes, check the media query
mq.addListener(function WidthChange(mq){
if(mq.matches){
//we are in a mobile size browser
$('#menu2').addClass('mobile');
$('#menu2').removeClass('f-nav');
} else{
// desktop browser
$('#menu2').addClass('f-nav');
$('#menu2').removeClass('mobile');
}
});
}
當您在比斷點大的屏幕上加載網站時,腳本將無法工作,因為您需要重新計算屏幕大小(在這種情況下刷新頁面)。 你需要在調整大小時獲得屏幕的寬度。 使用resize()方法,在其中放置測試條件,並將類分配給元素。 參考幫助您: http : //api.jquery.com/resize/
如果你想在JS中更改div的類,你可以這樣做:
document.getElementById("#YourId").className = "YourNewClass"
它只會改變你的類屬性:-)
像這樣,您還可以檢查使用哪個類,並執行您想要執行的操作。
編輯感謝Olaf Dietsche:這必須是一個重復的帖子,這里可以是你的答案: jquery,當窗口寬度改變時添加/刪除類
有幾種方法可以做到這一點:
看到它在行動: 小提琴
$(window).resize(function() {
if ($(window).width() < 1050) {
$selector.removeClass('my-class');
} else {
$selector.addClass('my-class');
}
}).resize(); // trigger resize event initially
不要忘記:你不必在$(document).ready
放置$(window).resize
。
看到它在行動: 小提琴
這里解釋了這種技術: http : //www.senaeh.de/media-query-variablen-javascript-auslesen/
基本原則:使用CSS偽元素設置變量並使用javascript獲取它。
即使使用了媒體查詢,如果必須使用Javascript,這種解決方法也很好,因為您不必兩次聲明斷點。
CSS
@media screen and (max-width: 1050px) {
body:after {
content: 'tablet';
display: none;
}
}
使用Javascript
var mode = window.getComputedStyle(document.body,':after').getPropertyValue('content');
請注意:IE <9不支持getComputedStyle
。 你必須使用像這樣的polyfill。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.