Javascript jquery css选择器不工作
我试图获得窗口的宽度和高度+一个div的宽度和高度,以找到调整后的宽度。我还试图用jquery绝对定位div,但我的代码不起作用。我将在下面提供代码 CSS:Javascript jquery css选择器不工作,javascript,jquery,css,Javascript,Jquery,Css,我试图获得窗口的宽度和高度+一个div的宽度和高度,以找到调整后的宽度。我还试图用jquery绝对定位div,但我的代码不起作用。我将在下面提供代码 CSS: #inner { width: 500px; height: 300px; background: #ff0000; } $(document).ready(function() { var screenWidth = $(window).width(); var screenHeight = $(window).he
#inner {
width: 500px; height: 300px;
background: #ff0000;
}
$(document).ready(function() {
var screenWidth = $(window).width();
var screenHeight = $(window).height();
var boxWidth = $("#inner").width();
var boxHeight = $("#inner").height();
var adjustedWidth = screenWidth - boxWidth;
var adjustedHeight = screenHeight - boxHeight;
$("#inner").css('position', 'absolute');
$("#inner").css('top', adjustedWidth + 'px');
$("#inner").css('left', adjustedHeight + 'px');
});
jQuery:
#inner {
width: 500px; height: 300px;
background: #ff0000;
}
$(document).ready(function() {
var screenWidth = $(window).width();
var screenHeight = $(window).height();
var boxWidth = $("#inner").width();
var boxHeight = $("#inner").height();
var adjustedWidth = screenWidth - boxWidth;
var adjustedHeight = screenHeight - boxHeight;
$("#inner").css('position', 'absolute');
$("#inner").css('top', adjustedWidth + 'px');
$("#inner").css('left', adjustedHeight + 'px');
});
我在jQuery中做错了什么?希望我的解释已经很清楚了。如果你试图在右下角对齐你的div,那么你混淆了top->adjustedWidth和left->adjustedHeight:
$("#inner").css('top', adjustedWidth + 'px');
$("#inner").css('left', adjustedHeight + 'px');
当它应该是相反的方式:
$("#inner").css('top', adjustedHeight + 'px');
$("#inner").css('left', adjustedWidth + 'px');
除此之外,你的代码
另外,在尝试更改CSS宽度或高度时,不需要添加“px”。无需使用JavaScript。绝对定位时,
左
和顶
不是唯一可以使用的东西;相反,您可以在适当的情况下使用右侧
和底部
。例如,要在您看起来正在做的事情时将某物放置在右下角,可以使用以下命令:
什么{
位置:绝对位置;
右:0;
底部:0;
宽度:300px;
高度:150像素;
背景:红色;
}
如果您的代码包括获取组件的大小(尤其是页面上有图像),那么您希望将代码放入
加载处理程序,而不是就绪处理程序,因为就绪是在下载所有图像之前执行的,之后页面的大小可能会有所不同
您的顶部
和左侧
也应该互换
$(document).on('load', function() {
var screenWidth = $(window).width();
var screenHeight = $(window).height();
var boxWidth = $("#inner").width();
var boxHeight = $("#inner").height();
var adjustedWidth = screenWidth - boxWidth;
var adjustedHeight = screenHeight - boxHeight;
$("#inner").css('position', 'absolute');
$("#inner").css('top', adjustedHeight + 'px');
$("#inner").css('left', adjustedWidth + 'px');
});
“我的代码不工作”是什么意思?你有错误吗?你没有得到你期望的结果吗?你得到了什么,你期望得到什么?请创建一个演示。你能发布相关的HTML以防它在问题中起作用吗?尝试了一个JSFIDLE:它似乎工作得很好(检查结果的来源)。您可能没有正确地包含jQuery,或者您的HTML不正确。