最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - javascript element.style.left Not working - Stack Overflow

programmeradmin2浏览0评论

Setting element top,left via javascript stops working,Perviously it was working perfectly.

ifrmObj.style.left = 100;
ifrmObj.style.top = 150;

Now i have to add a 'px' with number. What is the change that i made is the reason for this issue

Setting element top,left via javascript stops working,Perviously it was working perfectly.

ifrmObj.style.left = 100;
ifrmObj.style.top = 150;

Now i have to add a 'px' with number. What is the change that i made is the reason for this issue

Share Improve this question edited Sep 30, 2021 at 19:44 j08691 208k32 gold badges268 silver badges280 bronze badges asked Sep 1, 2015 at 6:31 Vishnuprabhu GopalakrishnanVishnuprabhu Gopalakrishnan 1231 gold badge2 silver badges12 bronze badges 4
  • 4 Try ifrmObj.style.left = 100 + 'px'; – Tushar Commented Sep 1, 2015 at 6:31
  • But without px its worked for me. – Vishnuprabhu Gopalakrishnan Commented Sep 1, 2015 at 9:33
  • Remove <!DOCTYPE HTML> from your file and it will work fine. The "px" is required by the html standards. So when you tell your browser it is reading html, it follows a strict set of rules. Those rules can be ignored if you know what you are doing. – user14803978 Commented Aug 27, 2021 at 5:24
  • Do not forget to suffix the number with 'px' – Prashant Zombade Commented Sep 22, 2021 at 12:54
Add a comment  | 

3 Answers 3

Reset to default 12

Use position first then left or top will work like,

Syntax:

object.style.position="static|absolute|fixed|relative|initial|inherit" 

For egs,

ifrmObj.style.position='absolute';//relative or fixed

To add px in your numbers,

For static numbers

ifrmObj.style.left = '100px';
ifrmObj.style.top = '150px';

For variables numbers

var x=100,y=150;
ifrmObj.style.left = x+'px';
ifrmObj.style.top = y+'px';

And if you are using jquery then use css() in one go like,

$(ifrmObj).css({'left':'100px','top':'150px','position':'absolute'});

A simple solution to this issue that was not addressed. Remove the following from the top of your html file that is using the script:

<!DOCTYPE HTML>

I dont know what that reason.. and you can add to CSS code a class for ex:

HTML Code

<div id="div"> <p> abcd </p></div>

CSS Code

.edit-left {left: 0 ;}

JS

const handleClickProjects = () => {
     console.log("click")
        let element= document.getElementById("div");
        if (element.classList.contains("edit-left")) {
            element.classList.remove("edit-left")  
        }
        else {
            element.classList.add("edit-left")
        }
    }

This for ReactJS. For pure JS use addEventListener.... (this code has a default left arg)

发布评论

评论列表(0)

  1. 暂无评论