这是我的代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Box using Plugin</title>
<script>
(function ($) {
$.fn.boxPlugin = function (options) {
//default values
var settings = $.extend({
color: "green",
width: "100px",
height: "100px",
backgroundColor: "black",
imageURL: "",
display: "inline-block"
}, options);
$(this).addClass('boxAdded').css({ "color": settings.color, "width": settings.width, "height": settings.height, "background": settings.backgroundColor, "display": settings.display }).find('img').attr('src', settings.imageURL);
}
}(jQuery));
</script>
<style>
p {
margin: 0px;
}
</style>
<script>
$(function () {
$(".box").boxPlugin({ width: "200px", height: "200px", backgroundColor: "lightblue" });
$("#boxOne").boxPlugin({ width: "200px", height: "200px", backgroundColor: "lightblue", imageURL: "https://www.w3schools.com/images/w3schools_green.jpg" });
})
</script>
</head>
<body>
<p class="box"></p>
<p class="box"></p>
<p class="box"></p>
<p id="boxOne">
<img src="" />
</p>
</body>
</html>
如果我不将 imageURL 添加到选项中,那么宽度和高度就会设置好,它就可以正常工作。
但是当我添加 imageURL 选项时,图像会链接到它的来源,但段落会向下移动一点,为什么会这样?太奇怪了!
谢谢。
最佳答案
将您的 CSS
更改为:
p {
margin: 0px;
vertical-align: top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Box using Plugin</title>
<script>
(function ($) {
$.fn.boxPlugin = function (options) {
//default values
var settings = $.extend({
color: "green",
width: "100px",
height: "100px",
backgroundColor: "black",
imageURL: "",
display: "inline-block"
}, options);
$(this).addClass('boxAdded').css({ "color": settings.color, "width": settings.width, "height": settings.height, "background": settings.backgroundColor, "display": settings.display }).find('img').attr('src', settings.imageURL);
}
}(jQuery));
</script>
<style>
p {
margin: 0px;
vertical-align: top;
}
</style>
<script>
$(function () {
$(".box").boxPlugin({ width: "200px", height: "200px", backgroundColor: "lightblue" });
$("#boxOne").boxPlugin({ width: "200px", height: "200px", backgroundColor: "lightblue", imageURL: "https://www.w3schools.com/images/w3schools_green.jpg" });
})
</script>
</head>
<body>
<p class="box"></p>
<p class="box"></p>
<p class="box"></p>
<p id="boxOne">
<img src="" />
</p>
</body>
</html>
关于jquery - 为什么当我使用 jQuery 自定义插件将 src 添加到图像时,该段落被下移了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45344062/