$(window).width()与媒体查询不一样

我在一个项目上使用Twitter Bootstrap。除了默认的引导样式外,我还添加了一些自己的引导样式

//My styles
@media (max-width: 767px)
{
//CSS here
}

当viewport的宽度小于767px时,我还使用jQuery来改变页面上某些元素的顺序。

$(document).load($(window).bind("resize", checkPosition));


function checkPosition()
{
if($(window).width() < 767)
{
$("#body-container .main-content").remove().insertBefore($("#body-container .left-sidebar"));
} else {
$("#body-container .main-content").remove().insertAfter($("#body-container .left-sidebar"));
}
}

我遇到的问题是,由$(window).width()计算的宽度和由CSS计算的宽度似乎不一样。当$(window).width()返回767时,css将视口宽度计算为751,因此似乎有16px的差异。

有人知道是什么导致了这个问题吗?我该如何解决这个问题?人们建议滚动条的宽度没有被考虑在内,使用$(window).innerWidth() < 751是正确的方法。然而,理想情况下,我想找到一个解决方案,计算滚动条的宽度,这是与我的媒体查询一致(例如,这两个条件都检查值767)。因为不是所有浏览器的滚动条宽度都是16px?

290484 次浏览

这可能是由于scrollbar,使用innerWidth而不是width

if($(window).innerWidth() <= 751) {
$("#body-container .main-content").remove()
.insertBefore($("#body-container .left-sidebar"));
} else {
$("#body-container .main-content").remove()
.insertAfter($("#body-container .left-sidebar"));
}

你也可以得到viewport

function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

以上代码< a href = " http://andylangton.co。英国/博客/开发/ get-viewport-size-width-and-height-javascript noreferrer“rel = > < / >来源

试试这个

if (document.documentElement.clientWidth < 767) {
// scripts
}

更多参考请单击here

检查媒体查询更改的CSS规则。这保证总是有效的。

http://www.fourfront.us/blog/jquery-window-width-and-media-queries

HTML:

<body>
...
<div id="mobile-indicator"></div>
</body>

Javascript:

function isMobileWidth() {
return $('#mobile-indicator').is(':visible');
}

CSS:

#mobile-indicator {
display: none;
}


@media (max-width: 767px) {
#mobile-indicator {
display: block;
}
}

是的,这是由于滚动条。正确答案来源:在这里输入链接描述

function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

也许更好的做法是不对文档的宽度进行js作用域,而是通过css @media查询进行某种更改。使用这种方法,你可以确保JQuery函数和css的变化是同时发生的。

css:

#isthin {
display: inline-block;
content: '';
width: 1px;
height: 1px;
overflow: hidden;
}


@media only screen and (max-width: 990px) {
#isthin {
display: none;
}
}

jquery:

$(window).ready(function(){
isntMobile = $('#isthin').is(":visible");
...
});


$(window).resize(function(){
isntMobile = $('#isthin').is(":visible");
...
});

我最近也遇到了同样的问题——同样是Bootstrap 3。

无论是$.width()或$. innerwidth()将为您工作。

我想到的最好的解决方案-是专门为BS3量身定制的-
检查.container元素的宽度。

你可能知道.container元素是如何工作的,
它是唯一的元素,将给你当前宽度设置由BS css规则

它是这样的

bsContainerWidth = $("body").find('.container').width()
if (bsContainerWidth <= 768)
console.log("mobile");
else if (bsContainerWidth <= 950)
console.log("small");
else if (bsContainerWidth <= 1170)
console.log("medium");
else
console.log("large");

如果你不需要支持IE9,你可以使用window.matchMedia() (MDN文档)。

function checkPosition() {
if (window.matchMedia('(max-width: 767px)').matches) {
//...
} else {
//...
}
}

window.matchMedia与CSS媒体查询完全一致,浏览器的支持也很好

更新:

如果你必须支持更多的浏览器,你可以使用Modernizr的mq方法,它支持所有理解CSS媒体查询的浏览器。

if (Modernizr.mq('(max-width: 767px)')) {
//...
} else {
//...
}

Javascript提供了不止一种方法来检查视口宽度。如您所注意到的,innerWidth不包括工具栏宽度,而且工具栏宽度在不同的系统中是不同的。还有outerWidth选项,它将包括工具栏宽度。Mozilla Javascript API声明:

< p >窗口。outerWidth获取浏览器窗口外部的宽度。 它表示包括边栏在内的整个浏览器窗口的宽度 (如果展开),窗口chrome和窗口大小调整边框/句柄

javascript的状态是这样的,我们不能在每个平台上的每个浏览器中都依赖于outerWidth的特定含义。

outerWidth旧的移动浏览器上不太支持,尽管它在主流桌面浏览器和大多数较新的智能手机浏览器中都得到支持。

正如ausi指出的,matchMedia将是一个很好的选择,因为CSS更好地标准化了(matchMedia使用JS读取CSS检测到的视口值)。但即使有了公认的标准,弱智的浏览器仍然存在,忽视他们(IE <在这种情况下,这使得matchMedia不是很有用,至少直到XP死亡)。

总结中,如果你只是为桌面浏览器和更新的移动浏览器开发,outerWidth应该用一些警告给你你正在寻找的东西。

使用

window.innerWidth

这解决了我的问题

解决方案,总是工作,并与CSS媒体查询同步。

为主体添加一个div

<body>
...
<div class='check-media'></div>
...
</body>

添加样式,并通过进入特定的媒体查询更改它们

.check-media{
display:none;
width:0;
}
@media screen and (max-width: 768px) {
.check-media{
width:768px;
}
...
}

然后在JS中通过输入媒体查询来检查您正在更改的样式

if($('.check-media').width() == 768){
console.log('You are in (max-width: 768px)');
}else{
console.log('You are out of (max-width: 768px)');
}

所以一般来说,你可以通过输入特定的媒体查询来检查任何正在更改的样式。

下面是处理媒体询问的一个不太复杂的技巧。跨浏览器支持有点受限,因为它不支持移动IE。

     if (window.matchMedia('(max-width: 694px)').matches)
{
//do desired changes
}

更多细节参见Mozilla的文档

这是前面提到的依赖于通过CSS更改内容并通过Javascript读取的方法的替代方法。此方法不需要window.matchMedia或Modernizr。它也不需要额外的HTML元素。它通过使用HTML伪元素来“存储”断点信息:

body:after {
visibility: hidden;
height: 0;
font-size: 0;
}


@media (min-width: 20em) {
body:after {
content: "mobile";
}
}


@media (min-width: 48em) {
body:after {
content: "tablet";
}
}


@media (min-width: 64em) {
body:after {
content: "desktop";
}
}

我使用body作为例子,你可以使用任何HTML元素。你可以在伪元素的content中添加任何你想要的字符串或数字。不一定要“移动”等等。

现在我们可以通过以下方式从Javascript中读取这些信息:

var breakpoint = window.getComputedStyle(document.querySelector('body'), ':after').getPropertyValue('content').replace(/"/g,'');


if (breakpoint === 'mobile') {
doSomething();
}

通过这种方式,我们总是可以确保断点信息是正确的,因为它直接来自CSS,我们不需要通过Javascript来获得正确的屏幕宽度。

最好的跨浏览器解决方案是使用Modernizr.mq

< em >链接:< / em > https://modernizr.com/docs/#mq

Modernizr。Mq允许您以编程方式检查当前浏览器窗口状态是否与媒体查询匹配。

var query = Modernizr.mq('(min-width: 900px)');
if (query) {
// the browser window is larger than 900px
}

请注意浏览器不支持媒体查询(例如旧的IE) mq总是返回false。

实现光滑滑块,并根据分辨率在块中显示不同数量的幻灯片(jQuery)

   if(window.matchMedia('(max-width: 768px)').matches) {
$('.view-id-hot_products .view-content').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
dots: true,
});
}


if(window.matchMedia('(max-width: 1024px)').matches) {
$('.view-id-hot_products .view-content').slick({
infinite: true,
slidesToShow: 4,
slidesToScroll: 4,
dots: true,
});
}
if(window.matchMedia('(max-width: 768px)').matches)
{
$(".article-item").text(function(i, text) {


if (text.length >= 150) {
text = text.substring(0, 250);
var lastIndex = text.lastIndexOf(" ");
text = text.substring(0, lastIndex) + '...';
}


$(this).text(text);


});


}

试试这个

getData(){
if(window.innerWidth <= 768) {
alert('mobile view')
return;
}


//else function will work


let body= {
"key" : 'keyValue'
}
this.dataService.getData(body).subscribe(
(data: any) => {
this.myData = data
}
)
}

我做什么;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
...

然后在任意位置调用width变量。

您需要将getWidth()放在文档主体中,以确保计算滚动条宽度,否则浏览器的滚动条宽度将从getWidth()中减去。

如果你想每1秒检查一次屏幕宽度,你可以这样做

 setInterval(function() {
if (window.matchMedia('(max-width: 767px)').matches) {
alert('here')
} else {
alert('i am ')
}
}, 1000);