温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

jQuery如何实现点击替换图片特效

发布时间:2022-03-02 15:16:44 来源:亿速云 阅读:255 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关jQuery如何实现点击替换图片特效,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

  1,起因

  最近在工作中要实现自定义式的radio样式,而我们通常使用的时默认的样式,因为自己实在想不到解决的方法,于是开始搜索,最终看到了不错的解决办法,可以完美解决我们遇到的问题。

  2,原理

  大家都知道在写结构的时候,radio或checkbox都会跟随label一起使用,label的for属性值和input的id值相同的情况下,点击label就可以选中input,这里正是利用label 来覆盖我们的input默认样式,通过给label添加背景图片(美化的checkbox或radio),也就是在点击的过程中,我们是看不到默认的input的(给input设置z-index:-1),而点击的是label,通过不同的事件,加载不同的背景图片(这里是改变背景图片的位置)

  3,设置美化checkbox或radio的默认样式

  (1)页面结构

  Which genres do you like?

  Action / Adventure

  Comedy

  Epic / Historical

  Science Fiction

  Romance

  Western

  Caddyshack is the greatest movie of all time, right?

  Totally

  You must be kidding

  What's Caddyshack?

  (2)jquery code(前提必须引入jquery库)

  jQuery.fn.customInput=function(){

  $(this)。each(function(i){

  if($(this)。is('[type=checkbox],[type=radio]')){

  var input=$(this);

  //get the associated label using the input's id

  var label=$('label[for='+input.attr('id')+']');

  //get type,for classname suffix

  var inputType=(input.is('[type=checkbox]')) ? 'checkbox' : 'radio';

  //wrap the input + label in a div

  $('

  //find all inputs in this set using the shared name attribute

  var allInputs=$('input[name='+input.attr('name')+']');

  //necessary for browsers that don't support the :hover pseudo class on labels

  label.hover(function(){

  $(this)。addClass('hover');

  if(inputType=='checkbox' && input.is(':checked')) {

  $(this)。addClass('checkedHover');

  }

  },function(){

  $(this)。removeClass('hover checkedHover');

  });

  //bind custom event, trigger it, bind click,focus,blur events

  input.bind('updateState',function(){

  if(input.is(':checked')){

  if(input.is(':radio')){

  allInputs.each(function(){

  $('label[for='+$(this)。attr('id')+']')。removeClass('checked');

  });

  };

  label.addClass('checked');

  } else {

  label.removeClass('checked checkedHover checkedFocus');

  }

  })

  。trigger('updateState')

  。click(function(){

  $(this)。trigger('updateState');

  })

  。focus(function(){

  label.addClass('focus');

  if(inputType=='checkbox' && input.is(':checked')) {

  $(this)。addClass('checkedFocus');

  }

  })

  。blur(function(){

  label.removeClass('focus checkedFocus');

  });

  }

  });

  }

  引入jquery库,再引入上面的代码后,就可以执行下面的代码

  $('input')。customInput();

  (3)生成的外层div

  如果你的代码结构是label和input成对写的话,那么在它们的外层就会生成一个div

关于“jQuery如何实现点击替换图片特效”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI