[英]Toggle behaviour based on screen width
The goal here is to make a page responsive and mobile friendly. 这里的目标是使页面响应和移动友好。
I show an invoice with all its details when on a desktop. 在台式机上时,我会显示发票及其所有详细信息。 But when the viewport is reduced, the details are hidden and can be toggled (hide/unhide) on clicking/tapping. 但是,当缩小视口时,细节将被隐藏,并且可以在单击/轻击时切换(隐藏/取消隐藏)。
So I have a trigger
and a target
class. 所以我有一个trigger
和一个target
类。
$('.trigger').click(function(){
$('.target').toggleClass('hide');
})
This works as expected if I add the hide
class to target
in my markup. 如果我将hide
类添加到标记中的target
,这将按预期工作。 But I cannot do that as they should appear unless the user views the page at a small screen. 但是我不能这样做,除非用户在小屏幕上查看页面,否则它们应该出现。 I can set display: none
in the media queries but that hides target for good. 我可以设置display: none
媒体查询中display: none
,但是可以永久隐藏目标。
What property of the target
element should I modify so that it hides itself when the screen size is reduced and I can toggle its view with the hide
class? 我应该修改target
元素的什么属性,以便在减小屏幕尺寸时隐藏自身,并可以使用hide
类切换其视图?
This all depends on what you are doing: 这一切都取决于您在做什么:
You could use JavaScript to detect the width and add specfic classes on the toggle to display it. 您可以使用JavaScript来检测宽度,并在切换器上添加特定的类以显示宽度。
$screenWidthCheck = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if ($screenWidthCheck > 1280) {
$("#page-content").addClass('active');
}
You could then add an even to it. 然后,您可以添加一个偶数。
$(window).resize(function() {
$screenWidthCheck = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if ($screenWidthCheck > 1280) {
$("#page-content").addClass('active');
}
});
A Javascript solution would be to add a hook to load
and resize
event handlers that would check the screen width and add/remove the class accordingly. Javascript解决方案是添加一个挂钩来load
和resize
事件处理程序的resize
事件处理程序将检查屏幕宽度并相应地添加/删除类。
$(window).on("load resize", function() {
//Assuming you consider anything >= 1240 as desktop
$('.target').toggleClass('hide', $(window).width() < 1240);
});
A CSS
solution: CSS
解决方案:
@media all and (min-width: 1240px) {
.target {
display: block;
}
}
@media all and (max-width: 1239px) {
.target {
display: none;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.