javascript 用 JS 改变 margin-left

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19435093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:35:00  来源:igfitidea点击:

change margin-left with JS

javascriptjquerycss

提问by Thomas Ayoub

I want a dynamical margin-left on a given div.

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

I tried this code :

我试过这个代码:

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

which doesn't work (the alert is here just for test purpose), the problem is coming from the ligne $('#search').css('margin-Left', size));but I can't find out where...

这不起作用(警报在这里仅用于测试目的),问题来自ligne,$('#search').css('margin-Left', size));但我无法找到......

I've tried with a lowercase lon margin-left and didn't work.

我试过l在 margin-left 上使用小写,但没有用。

回答by Arthur Weborg

Would the following work for you?

以下对你有用吗?

document.getElementById("search").style.marginLeft = size + "px";

回答by Ryan Anderson

Try using marginLeft, without the hypen.

尝试使用 marginLeft,不使用连字符。

jQuery.css() documentation: http://api.jquery.com/css/

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

回答by Giovanni Silveira

You need to specify the type of unit you want to use.

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

$('#search').css('margin-left', size + 'px');

回答by Harsha Venkatram

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

HTML

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

CSS

CSS

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

FIDDLE LINK

小提琴链接