下面的javascript
和css
代码在屏幕上以不同位置打印两个图像,并且效果很好。
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;
}
但是,我想在两个单独的CSS函数中设置这些图像的位置,而不是像我目前所做的那样在javascript
代码上定义它们的位置。我要执行的伪代码是这样的:
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;
}
唯一的区别是,我想使用top
声明left
和css
属性,而不是使用javascript声明。我该怎么办?
答案 0 :(得分:0)
css必须是:
img {
position:absolute;
width: 50px;
height: 50px;
top :150px;
left :50px;
}
img2 {
position:absolute;
width: 50px;
height: 50px;
top: 50px;
left:50px;
}
它是':'而不是'='
答案 1 :(得分:0)
正如评论中的Tyler Roper所述,只需在创建每个图像时向每个图像添加一个类即可解决问题...因此,这是为我工作的完整功能代码:
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;
}