The following javascript
and css
code prints two images on the screen with different positions and it works perfectly fine.
print_first_image(); print_second_image(); function print_first_image() { const img = document.body.appendChild(document.createElement('img')); img.src = 'https://i.stack.imgur.com/SjeyK.jpg?s=32&g=1'; img.style.top = '150px'; img.style.left = '50px'; } function print_second_image() { const img = document.body.appendChild(document.createElement('img')); img.src = 'https://i.stack.imgur.com/SjeyK.jpg?s=32&g=1'; img.style.top = '50px'; img.style.left = '50px'; }
img { position:absolute; width: 50px; height: 50px; }
However, I'd like to set the position of those images in two separated css functions instead of defining their position on the javascript
code as I'm currently doing. The pseudocode of what I want to do is something like this:
Javascript:
print_first_image();
print_second_image();
function print_first_image() {
const img = document.body.appendChild(document.createElement('img'));
img.src = 'https://i.stack.imgur.com/SjeyK.jpg?s=32&g=1';
}
function print_second_image() {
const img = document.body.appendChild(document.createElement('img2'));
img.src = 'https://i.stack.imgur.com/SjeyK.jpg?s=32&g=1';
}
css:
img {
position:absolute;
width: 50px;
height: 50px;
top: 150px;
left: 50px;
}
img2 {
position:absolute;
width: 50px;
height: 50px;
top: 50px;
left: 50px;
}
The only difference is that I want to declare the top
and left
attributes with css
instead of doing it with javascript. How can I do it?
the css must be:
img {
position:absolute;
width: 50px;
height: 50px;
top :150px;
left :50px;
}
img2 {
position:absolute;
width: 50px;
height: 50px;
top: 50px;
left:50px;
}
it's ':' not '='
As Tyler Roper stated in the comments simply adding a class to each image when I create them solves the problem... So here is the complete functional code that worked for me:
print_first_image(); print_second_image(); function print_first_image() { const img = document.body.appendChild(document.createElement('img')); img.classList.add("image1"); img.src = 'https://i.stack.imgur.com/SjeyK.jpg?s=32&g=1'; } function print_second_image() { const img = document.body.appendChild(document.createElement('img')); img.classList.add("image2"); img.src = 'https://i.stack.imgur.com/SjeyK.jpg?s=32&g=1'; }
.image1 { position:absolute; width: 50px; height: 50px; top: 50px; left: 50px; } .image2 { position:absolute; width: 50px; height: 50px; top: 150px; left: 50px; }
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.