首页 web前端 html教程 html中如何给图片添加点击事件的详解

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

Jun 19, 2017 am 09:54 AM
html

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

jQuery 事件 - bind() 方法 —— 定义和用法

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

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

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

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

  $(selector).bind(event,data,function)
登录后复制

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

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

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

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

实例:

//直接给所有img标签绑定click事件
$("img").click(function(){
   alert('你点击了图片');
})
 
//使用bind方法绑定click事件
$("img").bind("click",function(){
   alert('你点击了图片');
})
登录后复制

Html 的img标签添加点击事件

package com.topnews;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.topnews.base.BaseActivity;
import com.topnews.bean.NewsEntity;
import com.topnews.service.NewsDetailsService;
import com.topnews.tool.BaseTools;
import com.topnews.tool.DataTools;
import com.topnews.tool.DateTools;

@SuppressLint("JavascriptInterface")
public class DetailsActivity extends BaseActivity {
	private TextView title;
	private ProgressBar progressBar;
	private FrameLayout customview_layout;
	private String news_url;
	private String news_title;
	private String news_source;
	private String news_date;
	private NewsEntity news;
	private TextView action_comment_count;
	WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.details);
		setNeedBackGesture(true);// 设置需要手势监听
		getData();
		initView();
		initWebView();
	}

	/* 获取传递过来的数据 */
	private void getData() {
		news = (NewsEntity) getIntent().getSerializableExtra("news");
		news_url = news.getSource_url();
		news_title = news.getTitle();
		news_source = news.getSource();
		news_date = DateTools.getNewsDetailsDate(String.valueOf(news.getPublishTime()));
	}

	private void initWebView() {
		webView = (WebView) findViewById(R.id.wb_details);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		if (!TextUtils.isEmpty(news_url)) {
			WebSettings settings = webView.getSettings();
			settings.setJavaScriptEnabled(true);// 设置可以运行JS脚本
			// settings.setTextZoom(120);//Sets the text zoom of the page in
			// percent. The default is 100.
			settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
			// settings.setUseWideViewPort(true); //打开页面时, 自适应屏幕
			// settings.setLoadWithOverviewMode(true);//打开页面时, 自适应屏幕
			settings.setSupportZoom(false);// 用于设置webview放大
			settings.setBuiltInZoomControls(false);
			webView.setBackgroundResource(R.color.transparent);
			// 添加js交互接口类,并起别名 imagelistner
			webView.addJavascriptInterface(new JavascriptInterface(getApplicationContext()), "imagelistner");
			webView.setWebChromeClient(new MyWebChromeClient());
			webView.setWebViewClient(new MyWebViewClient());
			Log.i("info", "news_url:" + news_url);
			Log.i("info", "news_title:" + news_title);
			Log.i("info", "news_source:" + news_source);
			Log.i("info", "news_date:" + news_date);
			new MyAsnycTask().execute(news_url, news_title, news_source + " " + news_date);
		}
	}

	private void initView() {
		title = (TextView) findViewById(R.id.title);
		progressBar = (ProgressBar) findViewById(R.id.ss_htmlprogessbar);
		customview_layout = (FrameLayout) findViewById(R.id.customview_layout);
		// 底部栏目
		action_comment_count = (TextView) findViewById(R.id.action_comment_count);

		progressBar.setVisibility(View.VISIBLE);
		title.setTextSize(13);
		title.setVisibility(View.VISIBLE);
		title.setText(news_url);
		action_comment_count.setText(String.valueOf(news.getCommentNum()));
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
	}

	private class MyAsnycTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... urls) {
			String data = NewsDetailsService.getNewsDetails(urls[0], urls[1], urls[2]);
			Log.i("info", "MyAsnycTask.data:" + data);
			return data;
		}

		@Override
		protected void onPostExecute(String data) {
			webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
		}
	}

	// 注入js函数监听
	private void addImageClickListner() {
		// 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,在还是执行的时候调用本地接口传递url过去
		webView.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName(\"img\");" + "var imgurl=&#39;&#39;; "
				+ "for(var i=0;i<objs.length;i++)  " + "{" + "imgurl+=objs[i].src+&#39;,&#39;;" + "    objs[i].onclick=function()  " + "    {  "
				+ "        window.imagelistner.openImage(imgurl);  " + "    }  " + "}" + "})()");
	}

	// js通信接口
	public class JavascriptInterface {

		private Context context;

		public JavascriptInterface(Context context) {
			this.context = context;
		}

		public void openImage(String img) {

			//
			String[] imgs = img.split(",");
			ArrayList<String> imgsUrl = new ArrayList<String>();
			for (String s : imgs) {
				imgsUrl.add(s);
				Log.i("图片的URL>>>>>>>>>>>>>>>>>>>>>>>", s);
			}
			Intent intent = new Intent();
			intent.putStringArrayListExtra("infos", imgsUrl);
			intent.setClass(context, ImageShowActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		}
	}

	// 监听
	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			view.getSettings().setJavaScriptEnabled(true);
			super.onPageFinished(view, url);
			// html加载完成之后,添加监听图片的点击js函数
			addImageClickListner();
			progressBar.setVisibility(View.GONE);
			webView.setVisibility(View.VISIBLE);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			view.getSettings().setJavaScriptEnabled(true);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			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);
		}
	}
}
登录后复制

// NewsDetailsService.java

package com.topnews.service;

import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.text.TextUtils;

public class NewsDetailsService {
	public static String getNewsDetails(String url, String news_title,
			String news_date) {
		Document document = null;
		String data = "<body>" +
				"<center><h2 style=&#39;font-size:16px;&#39;>" + news_title + "</h2></center>";
		data = data + "<p align=&#39;left&#39; style=&#39;margin-left:10px&#39;>" 
				+ "<span style=&#39;font-size:10px;&#39;>" 
				+ news_date
				+ "</span>" 
				+ "</p>";
		data = data + "<hr size=&#39;1&#39; />";
		try {
			document = Jsoup.connect(url).timeout(9000).get();
			Element element = null;
			if (TextUtils.isEmpty(url)) {
				data = "";
				element = document.getElementById("memberArea");
			} else {
				element = document.getElementById("artibody");
			}
			if (element != null) {
				data = data + element.toString();
			}
			data = data + "</body>";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}
}
登录后复制

以上是html中如何给图片添加点击事件的详解的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
威尔R.E.P.O.有交叉游戏吗?
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

HTML 中的表格边框 HTML 中的表格边框 Sep 04, 2024 pm 04:49 PM

HTML 表格边框指南。在这里,我们以 HTML 中的表格边框为例,讨论定义表格边框的多种方法。

HTML 左边距 HTML 左边距 Sep 04, 2024 pm 04:48 PM

HTML 左边距指南。在这里,我们讨论 HTML margin-left 的简要概述及其示例及其代码实现。

HTML 中的嵌套表 HTML 中的嵌套表 Sep 04, 2024 pm 04:49 PM

这是 HTML 中嵌套表的指南。这里我们讨论如何在表中创建表以及相应的示例。

HTML 表格布局 HTML 表格布局 Sep 04, 2024 pm 04:54 PM

HTML 表格布局指南。在这里,我们详细讨论 HTML 表格布局的值以及示例和输出。

HTML 输入占位符 HTML 输入占位符 Sep 04, 2024 pm 04:54 PM

HTML 输入占位符指南。在这里,我们讨论 HTML 输入占位符的示例以及代码和输出。

HTML 有序列表 HTML 有序列表 Sep 04, 2024 pm 04:43 PM

HTML 有序列表指南。在这里我们还分别讨论了 HTML 有序列表和类型的介绍以及它们的示例

在 HTML 中移动文本 在 HTML 中移动文本 Sep 04, 2024 pm 04:45 PM

HTML 中的文本移动指南。在这里我们讨论一下marquee标签如何使用语法和实现示例。

HTML onclick 按钮 HTML onclick 按钮 Sep 04, 2024 pm 04:49 PM

HTML onclick 按钮指南。这里我们分别讨论它们的介绍、工作原理、示例以及各个事件中的onclick事件。

See all articles