最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change (AddRemove) CSS Class On Mobile With JS or jQuery - Stack Overflow

programmeradmin3浏览0评论

How can I change ten on desktop to three on mobile with JS or jQuery or SemanticUI?

<div class="ui ten column grid">...</div>

If screen size is less than 700px, change ten to three.

How can I change ten on desktop to three on mobile with JS or jQuery or SemanticUI?

<div class="ui ten column grid">...</div>

If screen size is less than 700px, change ten to three.

Share Improve this question edited Oct 3, 2020 at 13:18 Rodrigo 1061 gold badge1 silver badge7 bronze badges asked Oct 3, 2020 at 9:25 emretosunkayaemretosunkaya 3851 gold badge5 silver badges13 bronze badges 4
  • 1 If you are okay with a non-JS solution - you can check out CSS media queries. They can address this scenario easily without having to change the class. – Soubhik Mondal Commented Oct 3, 2020 at 9:34
  • 2 This is duplicate: stackoverflow.com/questions/20469816/… – MaxiGui Commented Oct 3, 2020 at 9:43
  • 1 @SoubhikMondal grid column css (one to ten) is from semanticui, there are defined css codes for "ten" and "three"? which is better: adding js to change class or duplicating same css for @media? It seems more advantageous to change it with JS according to my need now. Thanks all. – emretosunkaya Commented Oct 3, 2020 at 9:53
  • Does this answer your question? Jquery, Remove class when width screen is 1050px – ksav Commented Oct 17, 2020 at 4:27
Add a comment  | 

3 Answers 3

Reset to default 9

You could use $(window).width() < 700 and check if width < 700 then removeClass ten and addClass three.

This function will run even if you resize you window manually via mouse.

//Resize window
function resize() {
  if ($(window).width() < 700) {
    $('.myDiv').removeClass('ten').addClass('three');
  }
}

Runable Example:

//Resize window
function resize() {
  if ($(window).width() < 700) {
    $('.myDiv').removeClass('ten').addClass('three');
  }
}

//watch window resize
$(window).on('resize', function() {
  resize()
});
.ten {
  background: green;
}

.three {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ui ten column grid myDiv">My Div</div>

Try this code for JQuery:

if ($(window).width() < 700) {
$("...").removeClass("ten");
$("...").addClass("three");
} else {
$("...").removeClass("three");
$("...").addClass("ten");
}

Use this example

if ( window.innerWidth < 700 ) {
    document.querySelector("div").classList.add('three');
    document.querySelector("div").classList.remove('ten');
}
发布评论

评论列表(0)

  1. 暂无评论