下面有两个div。 Div“ one”直接加载图像。 如何使用脚本“远程”加载图像,基本上就是说“将该图像加载到div二”?该图像必须加载到文本后面。
.text1 {
margin: -150px 0px 0px 70px
}
<div id="one">
<img src="https://cdn.images.express.co.uk/img/dynamic/25/590x/Great-Pyramid-of-Giza-secret-mystery-energy-996924.jpg?r=1533059304339" width="100%" height="auto" alt="image">
<P class="text1">This is a test text</p>
</div>
<div id="two">
<P class="text1">This is a test text</p>
</div>
答案 0 :(得分:1)
以编程方式创建图像元素并将其插入到两个元素中。
// Create image element
const img = document.createElement('img');
img.setAttribute('src', 'https://cdn.images.express.co.uk/img/dynamic/25/590x/Great-Pyramid-of-Giza-secret-mystery-energy-996924.jpg?r=1533059304339');
// Insert it into the two element
const two = document.querySelector('#two');
two.insertBefore(img, two.firstChild);
#one, #two {
position: relative;
display: inline-block;
}
.text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
padding: 10px;
background-color: rgba(0,0,0,0.5);
border-radius: 5px;
}
img {
max-width: 100%;
}
<div id="one">
<img src="https://cdn.images.express.co.uk/img/dynamic/25/590x/Great-Pyramid-of-Giza-secret-mystery-energy-996924.jpg?r=1533059304339">
<p class="text">This is a test text</p>
</div>
<div id="two">
<p class="text">This is a test text</p>
</div>
答案 1 :(得分:0)
var div = document.getElementById("two") // Get the div that You want to insert the image to
var img = document.createElement("img") // Create image element
// Set image source to url of a photo
img.src = "https://cdn.images.express.co.uk/img/dynamic/25/590x/Great-Pyramid-of-Giza-secret-mystery-energy-996924.jpg?r=1533059304339"
// Set image width attribute
img.width = "100%"
// Set image height attribute
img.height = "auto"
// Set image alt attribute
img.alt = "image"
// Insert image into the div
div.insertBefore(img, div.firstChild)
这是您将图像添加到文本段落之前ID为“ 2”的div中的方法。
答案 2 :(得分:0)
// Get your image in div#one
var img = document.querySelector('#one img');
// Get your div#two where to add the image
var two = document.querySelector('#two');
// Insert the img as 1st child of div#two
// Use cloneNode() to keep a copy in div#one
two.insertBefore(img.cloneNode(), two.firstChild);
.text1 {
margin: -150px 0px 0px 70px
}
<div id="one">
<img src="https://cdn.images.express.co.uk/img/dynamic/25/590x/Great-Pyramid-of-Giza-secret-mystery-energy-996924.jpg?r=1533059304339" width="100%" height="auto" alt="image">
<p class="text1">This is a test text</p>
</div>
<div id="two">
<p class="text1">This is a test text</p>
</div>
答案 3 :(得分:0)
您可以创建图片标签,将该图片提供给源,然后将新创建的图片标签附加到div。
var newimg = $('<img>');
var imgsrc = 'https://cdn.images.express.co.uk/img/dynamic/25/590x/Great-Pyramid-of-Giza-secret-mystery-energy-996924.jpg?r=1533059304339'
newimg.attr('src', imgsrc);
newimg.appendTo('#two');
.text1 {
margin: -150px 0px 0px 70px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="two">
<P class="text1">This is a test text</p>
</div>