I made a kind of game in javascript and in this game there are some divs which are horizontally moving with different transition times. In this game there is a function which is called each 1/100
seconds. Then it first checks it position with:
$("class1").css("margin-left")
And now the weird thing: when I set the class in html like:
<div class = "class1"></div>
The .css("margin-left")
works perfectly, but when I don't set a class in html and I add the class in js like:
$("div:nth-child(6)").addClass("class1");
Then the $(theclass).css("margin-left")
give wrong outputs. I tried with the .position and .offset but those both didn't work for me.
My code:
function newBlock(block, marginTop, bgc, height, hoogte1, hoogte2, v, tijd){
block.css("background-color", bgc).css("height", height).css("margin-top", marginTop);
var movement1 = "movement1";
var movement2 = "movement2";
// if (positionPixelsBlockF > 0){
// positionPixelsBlockF = positionBlockF.slice(0, 3);
// }
setInterval(positie, 10);
function positie(){
tijd = tijd + 1;
if (v != 0){
block.addClass("i" + v);
$(".i" + v).css({"width": "50px", "display": "inline-block", "position": "absolute", "z-index": "20"});
var positionBlockF = $(".i" + v).css("margin-left");
var positionPixelsBlockF = positionBlockF.slice(0, 4);
$("#uitleg4").html(positionPixelsBlockF);
else if (v === 0){
var positionBlockF = $(".b1").css("margin-left");
var positionPixelsBlockF = positionBlockF.slice(0, 4);
Don't mind the incomplete use of the {}, but in my code that's fixed.
PS: using brackets
I believe you are missing a dot
before class1 selection, in jquery there are two types of elements selection either by class like $(".ElemnetClass")
OR by ID like $("#ElementID")
More info about .css()
This Is An Example Of Your Requirement
$(".class").css('margin-left','10px');// Some Px (or) percentage Your Based On Requirement
You Can Use This Type Also Firstly You Create One Class Of Your Requirements And Use Below Code
$("#ElementId").addClass('created classname Here');
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.