HTML页面中插入图片的几种方法

1 直接使用 img 标签
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<img src="picture.png" width="300" height="300">
</body>
</html>

2 用js创建一个 img 元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var myImage = document.createElement("img");
    myImage.src = "picture.png";
    myImage.width = 300;
    myImage.height = 300;
    document.body.appendChild(myImage);
</script>
</body>
</html>

3 使用 Image 对象,该Image构造函数创建了一个新的HTMLImageElement实例,它在功能上等同于document.createElement("img")

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var myImage = new Image(300, 300);
    myImage.src = "picture.png";
    document.body.appendChild(myImage);
</script>
</body>
</html>

4 使用innerHTML,动态添加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    document.body.innerHTML = '<img src= "picture.png" height="300" width="300" />';
</script>
</body>
</html>


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页