以下是 jQuery图片添加热链接代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery图片添加热链接代码</title>
<script src="js/jquery-1.11.3.min.js"></script>
<style>
*{padding: 0; margin: 0;}
.box{margin: 10px;}
.img_box{position: relative;}
.img_box .maodian{position: absolute; padding: 5px 10px; border-right: 5px; background: #000;
filter:alpha(opacity=40);
-moz-opacity:0.4;
opacity:0.4;
top:10px;
left:10px;
color:#FFF;
font-size: 12px;
font-family: "宋体";
cursor: pointer;
}
.maodian a{color: #FFF; text-decoration: none;}
</style>
<script>
$(function(){
var obj = null ;
$("#add").click(function(){
var title = $("input[name=title]").val();
var link = $("input[name=link]").val();
var html = "<p class='maodian'><a href='"+link+"'>"+title+"</a></p>";
$(".img_box").append(html);
});
$(".img_box").delegate(".maodian","mousedown",function(e){
obj = $(this);
if(obj.setCapture){
obj.setCapture();
}
$("input[name=title]").val(obj.find("a").text());
var _x = e.pageX - obj.offset().left;
var _y = e.pageY - obj.offset().top;
var oWidth = $(this).outerWidth();
var oHeight = $(this).outerHeight();
var x=0,y=0;
$(".img_box").bind("mousemove",function(e){
var img_position = $(".img_box").offset();
x = e.pageX -_x - img_position.left;
y = e.pageY -_y - img_position.top;
if(x<0){
x = 0;
}else if(x>($(".img_box img").width()-oWidth)){
x = $(".img_box img").width()-oWidth;
}
if(y<0){
y = 0;
}else if(y>($(".img_box img").height()-oHeight)){
y = $(".img_box img").height()-oHeight;
}
obj.css({"left":x,"top":y});
});
$(".img_box").bind("mouseup",function(){
$('.img_box').unbind("mousemove");
$(this).unbind("mouseup");
if(obj.releaseCapture){
obj.releaseCapture();
}
});
return false;
});
$(".img_box").delegate(".maodian","dblclick",function(){
$(this).remove();
})
$("#show").click(function(){
obj.find("a").text($("input[name=title]").val()).attr("href",link);
})
$(".img_box").delegate("a","click",function(){
return false;
})
})
</script>
</head>
<body>
<center>
<div class="box">
<input type="text" name="title">
<input type="text" name="link" value="http://">
<input type="button" value="添加链接" id="add">
<input type="button" value="编辑" id="show">
</div>
<div class="img_box">
<img src="images/55cc64813c330.jpg">
</div>
</center>
</body>
</html>