整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

html实现点击图片放大功能

<html>
    <head>
        <style>
            .over {position: fixed; left:0; top:0; width:100%; z-index:100;}
            .tempContainer {position:fixed; width:100%; margin-right:0px; margin-left:0px; text-align:center; z-index:101;}
        </style>
        <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    </head>
    <body>
        <div class="over"></div><!--背景层-->
        <div class="logoImg amplifyImg"><!--注意:此处的amlifyImg不可少-->
            < img src="test.jpg"/><!-- 此处是引入图片的路径 -->
        </div>
        <script>
            $(document).ready(function () {
                var imgsObj = $('.amplifyImg img');//需要放大的图像
                if(imgsObj){
                    $.each(imgsObj,function(){
                        $(this).click(function(){
                            var currImg = $(this);
                            coverLayer(1);
                            var tempContainer = $('<div class=tempContainer></div>');//图片容器
                            with(tempContainer){//width方法等同于$(this)
                                appendTo("body");
                                var windowWidth=$(window).width();
                                var windowHeight=$(window).height();
                                //获取图片原始宽度、高度
                                var orignImg = new Image();
                                orignImg.src =currImg.attr("src") ;
                                var currImgWidth= orignImg.width;
                                var currImgHeight = orignImg.height;
                                if(currImgWidth<windowWidth){//为了让图片不失真,当图片宽度较小的时候,保留原图
                                    if(currImgHeight<windowHeight){
                                        var topHeight=(windowHeight-currImgHeight)/2;
                                        if(topHeight>35){/*此处为了使图片高度上居中显示在整个手机屏幕中:因为在android,ios的微信中会有一个title导航,35为title导航的高度*/
                                            topHeight=topHeight-35;
                                            css('top',topHeight);
                                        }else{
                                            css('top',0);
                                        }
                                        html('< img border=0 src=' + currImg.attr('src') + '>');
                                    }else{
                                        css('top',0);
                                        html('< img border=0 src=' + currImg.attr('src') + ' height='+windowHeight+'>');
                                    }
                                }else{
                                    var currImgChangeHeight=(currImgHeight*windowWidth)/currImgWidth;
                                    if(currImgChangeHeight<windowHeight){
                                        var topHeight=(windowHeight-currImgChangeHeight)/2;
                                        if(topHeight>35){
                                            topHeight=topHeight-35;
                                            css('top',topHeight);
                                        }else{
                                            css('top',0);
                                        }
                                        html('< img border=0 src=' + currImg.attr('src') + ' width='+windowWidth+';>');
                                    }else{
                                        css('top',0);
                                        html('< img border=0 src=' + currImg.attr('src') + ' width='+windowWidth+'; height='+windowHeight+'>');
                                    }
                                }
                            }
                            tempContainer.click(function(){
                                $(this).remove();
                                coverLayer(0);
                            });
                        });
                    });
                }
                else{
                    return false;
                }
                //使用禁用蒙层效果
                function coverLayer(tag){
                    with($('.over')){
                        if(tag==1){
                            css('height',$(document).height());
                            css('display','block');
                            css('opacity',1);
                            css("background-color","#FFFFFF");
                            css("background-color","rgba(0,0,0,0.7)" );  //蒙层透明度
                        }
                        else{
                            css('display','none');
                        }
                    }
                }
            });
        </script>
    </body>
</html>

先使用jQuery选择器获取到想要绑定click事件的img元素,然后可以直接绑定click方法,也可以通过bind方法绑定。这里详细介绍一下bind方法。jQuery 事件 - bind() 方法 —— 定义和用法

html中如何给图片添加点击事件的详解


bind() 方法为被选元素添加一个或多个事件处理程序,并规定事件发生时运行的函数。

jQuery 事件 - bind() 方法 ——将事件和函数绑定到元素

规定向被选元素添加的一个或多个事件处理程序,以及当事件发生时运行的函数。

jQuery 事件 - bind() 方法——语法

1 $(selector).bind(event,data,function)

jQuery 事件 - bind() 方法——参数描述

event 必需。规定添加到元素的一个或多个事件。由空格分隔多个事件。必须是有效的事件。

data 可选。规定传递到函数的额外数据。

function 必需。规定当事件发生时运行的函数。

实例:


1 //直接给所有img标签绑定click事件

2 $("img").click(function(){

3 alert('你点击了图片');

4 })

5

6 //使用bind方法绑定click事件

7 $("img").bind("click",function(){

8 alert('你点击了图片');

9 })


Html 的img标签添加点击事件


1 package com.topnews;

2

3 import java.util.ArrayList;

4

5 import android.annotation.SuppressLint;

6 import android.app.Activity;

7 import android.app.Fragment;

8 import android.content.Context;

9 import android.content.Intent;

10 import android.graphics.Bitmap;

11 import android.os.AsyncTask;

12 import android.os.Bundle;

13 import android.text.TextUtils;

14 import android.util.Log;

15 import android.view.View;

16 import android.view.ViewGroup.LayoutParams;

17 import android.webkit.WebChromeClient;

18 import android.webkit.WebSettings;

19 import android.webkit.WebView;

20 import android.webkit.WebViewClient;

21 import android.webkit.WebSettings.LayoutAlgorithm;

22 import android.widget.Button;

23 import android.widget.FrameLayout;

24 import android.widget.ProgressBar;

25 import android.widget.TextView;

26

27 import com.topnews.base.BaseActivity;

28 import com.topnews.bean.NewsEntity;

29 import com.topnews.service.NewsDetailsService;

30 import com.topnews.tool.BaseTools;

31 import com.topnews.tool.DataTools;

32 import com.topnews.tool.DateTools;

33

34 @SuppressLint("JavascriptInterface")

35 public class DetailsActivity extends BaseActivity {

36 private TextView title;

37 private ProgressBar progressBar;

38 private FrameLayout customview_layout;

39 private String news_url;

40 private String news_title;

41 private String news_source;

42 private String news_date;

43 private NewsEntity news;

44 private TextView action_comment_count;

45 WebView webView;

46

47 @Override

48 protected void onCreate(Bundle savedInstanceState) {

49 // TODO Auto-generated method stub

50 super.onCreate(savedInstanceState);

51 setContentView(R.layout.details);

52 setNeedBackGesture(true);// 设置需要手势监听

53 getData();

54 initView();

55 initWebView();

56 }

57

58 /* 获取传递过来的数据 */

59 private void getData() {

60 news = (NewsEntity) getIntent().getSerializableExtra("news");

61 news_url = news.getSource_url();

62 news_title = news.getTitle();

63 news_source = news.getSource();

64 news_date = 65DateTools.getNewsDetailsDate(String.valueOf(news.getPublishTime()));

66 }

67

68 private void initWebView() {

69 webView = (WebView) findViewById(R.id.wb_details);

70 LayoutParams params = new 71LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

72 if (!TextUtils.isEmpty(news_url)) {

73 WebSettings settings = webView.getSettings();

74 settings.setJavaScriptEnabled(true);// 设置可以运行JS脚本

75 // settings.setTextZoom(120);//Sets the text zoom of the page in

76 // percent. The default is 100.

77 settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

78 // settings.setUseWideViewPort(true); //打开页面时, 自适应屏幕

79 // settings.setLoadWithOverviewMode(true);//打开页面时, 自适应屏幕

80 settings.setSupportZoom(false);// 用于设置webview放大

81 settings.setBuiltInZoomControls(false);

82 webView.setBackgroundResource(R.color.transparent);

83 // 添加js交互接口类,并起别名 imagelistner

84 webView.addJavascriptInterface(new 85JavascriptInterface(getApplicationContext()), "imagelistner");

86 webView.setWebChromeClient(new MyWebChromeClient());

87 webView.setWebViewClient(new MyWebViewClient());

88 Log.i("info", "news_url:" + news_url);

89 Log.i("info", "news_title:" + news_title);

90 Log.i("info", "news_source:" + news_source);

91 Log.i("info", "news_date:" + news_date);

92 new MyAsnycTask().execute(news_url, news_title, news_source + " " + 93news_date);

94 }

95 }

96

97 private void initView() {

98 title = (TextView) findViewById(R.id.title);

99 progressBar = (ProgressBar) findViewById(R.id.ss_htmlprogessbar);

100 customview_layout = (FrameLayout) 101findViewById(R.id.customview_layout);

102 // 底部栏目

103 action_comment_count = (TextView) 104findViewById(R.id.action_comment_count);

105

106 progressBar.setVisibility(View.VISIBLE);

107 title.setTextSize(13);

108 title.setVisibility(View.VISIBLE);

109 title.setText(news_url);

110 action_comment_count.setText(String.valueOf(news.getCommentNum()));

111 }

112

113 @Override

114 public void onBackPressed() {

115 super.onBackPressed();

116 overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);

117 }

118

119 private class MyAsnycTask extends AsyncTask<string, string,="" string=""> {

120

121 @Override

122 protected String doInBackground(String... urls) {

123 String data = NewsDetailsService.getNewsDetails(urls[0], urls[1], urls[2]);

124 Log.i("info", "MyAsnycTask.data:" + data);

125 return data;

126 }

127

128 @Override

129 protected void onPostExecute(String data) {

130 webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

131 }

132 }

133

134 // 注入js函数监听

135 private void addImageClickListner() {

136 // 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,在还是执137 行的时候调用本地接口传递url过去

138 webView.loadUrl("javascript:(function(){" + "var objs = 139document.getElementsByTagName(\"img\");" + "var imgurl=''; "

140 + "for(var i=0;i<objs.length;i++) "="" +="" "{"="" 141"imgurl+="objs[i].src+',';"" objs[i].onclick="function()" {="" 142window.imagelistner.openimage(imgurl);="" }="" "}"="" "})()");="" js通信接口="" 143public="" class="" javascriptinterface="" private="" context="" context;="" 144javascriptinterface(context="" context)="" this.context="context;" void="" 145openimage(string="" img)="" string[]="" imgs="img.split(",");" 146arraylist<string=""> imgsUrl = new ArrayList<string>();

147 for (String s : imgs) {

148 imgsUrl.add(s);

149 Log.i("图片的URL>>>>>>>>>>>>>>>>>>>>>>>", s);

150 }

151 Intent intent = new Intent();

152 intent.putStringArrayListExtra("infos", imgsUrl);

153 intent.setClass(context, ImageShowActivity.class);

154 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

155 context.startActivity(intent);

156 }

157 }

158

159 // 监听

160 private class MyWebViewClient extends WebViewClient {

161 @Override

162 public boolean shouldOverrideUrlLoading(WebView view, String url) {

163 return super.shouldOverrideUrlLoading(view, url);

164 }

165

166 @Override

167 public void onPageFinished(WebView view, String url) {

168 view.getSettings().setJavaScriptEnabled(true);

169 super.onPageFinished(view, url);

170 // html加载完成之后,添加监听图片的点击js函数

171 addImageClickListner();

172 progressBar.setVisibility(View.GONE);

173 webView.setVisibility(View.VISIBLE);

174 }

175

176 @Override

177 public void onPageStarted(WebView view, String url, Bitmap favicon) {

178 view.getSettings().setJavaScriptEnabled(true);

179 super.onPageStarted(view, url, favicon);

180 }

181

182 @Override

183 public void onReceivedError(WebView view, int errorCode, String description, 184String failingUrl)

185 {

progressBar.setVisibility(View.GONE);

super.onReceivedError(view, errorCode, description, failingUrl);

}

}

private class MyWebChromeClient extends WebChromeClient {

@Override

public void onProgressChanged(WebView view, int newProgress) {

// TODO Auto-generated method stub

if (newProgress != 100) {

progressBar.setProgress(newProgress);

}

super.onProgressChanged(view, newProgress);

}

}

}</string></objs.length;i++)></string,>


// NewsDetailsService.java


1 package com.topnews.service;

2

3 import java.io.IOException;

4 import org.jsoup.Jsoup;

5 import org.jsoup.nodes.Document;

6 import org.jsoup.nodes.Element;

7

8 import android.text.TextUtils;

9

10 public class NewsDetailsService {

11 public static String getNewsDetails(String url, String news_title,

12 String news_date) {

13 Document document = null;

14 String data = "" +

15 "<center><h2 style="'font-size:16px;'">" + news_title + "</h2></center>";

16 data = data + "<p align="'left'" style="'margin-left:10px'">"

17 + "<span style="'font-size:10px;'">"

18 + news_date

19 + "</span>"

20 + "</p>";

21 data = data + "<hr size="'1'">";

22 try {

23 document = Jsoup.connect(url).timeout(9000).get();

24 Element element = null;

25 if (TextUtils.isEmpty(url)) {

26 data = "";

27 element = document.getElementById("memberArea");

28 } else {

29 element = document.getElementById("artibody");

30 }

31 if (element != null) {

32 data = data + element.toString();

33 }

34 data = data + "";

35 } catch (IOException e) {

36 e.printStackTrace();

37 }

38 return data;

39 }

40 }

以上就是html中如何给图片添加点击事件的详解的详细内容,

原理是点击图片时,改变图片的宽度和高度。

下面是效果图:

1、未点击时图片

未点击时图片


2、点击后的图片

点击后的图片

HTML代码:

<img src="img/pic.jpg" id="images" width="100" height="100" />

jQuery核心代码:

<script>

$(document).ready(function() {

var img = $(this),t = true;//当t为true时,是正常状态下的

$("#images").click(function() {

if(t) {

t = false;

imgH = $(this).height(400);

imgW = $(this).width(400);

} else {

t = true;

imgH = $(this).height(100);

imgW = $(this).width(100);

}

});

});

</script>