简体   繁体   中英

change css style using javascript

hi in my php application i want to change the style using javascript

<div id="middle-cnt" class="ad-image-wrapper"><div class="ad-image" style="width: 1000px; height: 450px; top: 0px; left: 131px;"><img height="450" width="1000" src="images/Gallery2/4.jpg"><p class="ad-image-description" style="width: 1000px; bottom: 0px;"><table width="100%"><tbody><tr><td class="image-desc">Stevie III &ndash; 36" long x 24" wide - Oil on Canvas<div style="color: rgb(187, 167, 0); padding-left: 10px; position: absolute; top: 0pt; left: 450px; font-size: 35px; letter-spacing: 6px;">SOLD</div></td></tr></tbody></table></p></div></div>

In the baove code i want to change the div style left:0px ie <div id="middle-cnt" class="ad-image-wrapper" ><div class="ad-image" style="width: 1000px; height: 450px; top: 0px; left: 0px;"><img ..

I am using the script below.

function fnshowgallery(){
var elm=document.getElementById('middle-cnt').childNodes;

    var divElm=elm[0];
    divElm.style.Left='0px';


}

But it's not get the desired result.

Does any one know this?

But i don't know how.

document.getElementById("middle-cnt").childNodes[0].style.left = "0px";

这应该可以,如果不能,请仔细检查您的DOM结构。

如果您希望属性起作用,则元素也需要位置属性。

javascript is a case sensitive language. and it's camel case. So it's not Left but **left. It has to be:

divElm.style.left='0px';  

If I evaluate that javascript in my console with that HTML snippet, it works; the "left" styling is changed to 0px.

But , I think you need to have the parent (#middle-cnt) to have position:relative , and your div (.ad-image) with position:absolute . Maybe you have this in your stylesheet...

Might help if you say what browser(s) you have tested with, as well.

Rather than manipulate the CSS directly with JavaScript it's usually a better approach to only use JavaScript to set the CSS class name and leave all your CSS in your .css files. For example:

/* CSS */
.foo {
    height:450px;
    left:0;
    position:relative; /* or maybe absolute? */
    top:0;
    width:1000px;
}

Then change your JavaScript to something like:

var elm = document.getElementById('middle-cnt').childNodes[0];
if (elm) {
    var cssClass = (elm.className) ? ' foo' : 'foo';
    elm.className += cssClass;
}

Then, if you need to make any more changes to your CSS you shouldn't need to touch the Javascript.

But for the left property to work in your CSS you'll need to set the position property to either relative or absolute .

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