6

我想要给定 div 上的动态边距。

我试过这段代码:

window.onload = function()
{
    var pageWidth = window.innerWidth; 
    var size = (pageWidth - 200 ) / 2;
    $('#search').css('margin-Left', size));
    alert(size);
 };

这不起作用(警报在这里只是为了测试目的),问题来自 ligne$('#search').css('margin-Left', size));但我不知道在哪里......

我试过l在左边距上使用小写字母,但没有用。

4

4 回答 4

7

以下内容对您有用吗?

document.getElementById("search").style.marginLeft = size + "px";
于 2013-10-17T19:12:18.987 回答
1

您需要指定要使用的单位类型。

$('#search').css('margin-left', size + 'px');
于 2013-10-17T19:11:23.747 回答
0

尝试使用marginLeft,不带hypen。

jQuery.css() 文档:http ://api.jquery.com/css/

于 2013-10-17T19:09:00.893 回答
0

JAVASCRIPT

$(document).ready(function(e){
    alert('test');
    var pageWidth = parseInt($(window).innerWidth());
    alert(pageWidth);
    var size = (pageWidth - 200 ) / 2;
    $('#search').css('margin-left', size);
    alert(size);
})

HTML

<div id = 'search'></div>

CSS

#search
{
    height:100px;
    width:100px;
    background-color:#F00;
}

小提琴链接

于 2013-10-17T19:13:18.410 回答