简体   繁体   中英

change margin-left with JS

I want a dynamical margin-left on a given 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...

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

以下是否适合您?

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

Try using marginLeft, without the hypen.

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

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

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

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;
}

FIDDLE LINK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM