资讯专栏INFORMATION COLUMN

常见样式设计及DOM操作整理

KavenFan / 298人阅读

摘要:部分为不同链接添加不同样式跨浏览器灰度图动画背景清除浮动方法方法方法将浮动元素用一个不浮动的包裹起来表格宽度自适应任意阴影文本宽度自适应模糊文本网页加载动画

css部分 为不同链接添加不同样式
a[href^="http"]{
padding-right: 20px;
background: url(external.gif) no-repeat center right;
}
/* email */
a[href^="mailto:"]{
padding-right: 20px;
background: url(email.png) no-repeat center right;
}
/* pdf */
a[href$=".pdf"]{
padding-right: 20px;
background: url(pdf.png) no-repeat center right;
}
跨浏览器灰度图


  


动画背景
button{
background-image: linear-gradient(#5187c4, #1c2f45);
background-size: auto 200%;
background-position: 0 100%;
transition: background-position 0.5s;
}
button:hover {
background-position: 0 0;
}
清除浮动
/*方法1*/
.clear-fix{
  clear: both;
  display: block;
  height: 0;
  overflow: hidden;
}
/*IE*/
.clear{
  overflow: auto; zoom: 1; /*IE6*/
}
/*方法2*/
&:after{
  content: "";
  display: block;
  height: 0;
  overflow: hidden;
  clear: both;
}
/*方法3*/
/*将浮动元素用一个不浮动的 div 包裹起来*/
表格宽度自适应
td {
white-space: nowrap;
}
任意阴影
.box-shadow {
background-color: #FF8020;
width: 160px;
height: 90px;
margin-top: -45px;
margin-left: -80px;
position: absolute;
top: 50%;
left: 50%;
}
.box-shadow:after {
content: "";
width: 150px;
height: 1px;
margin-top: 88px;
margin-left: -75px;
display: block;
position: absolute;
left: 50%;
z-index: -1;
-webkit-box-shadow: 0px 0px 8px 2px #000000;
-moz-box-shadow: 0px 0px 8px 2px #000000;
box-shadow: 0px 0px 8px 2px #000000;
}
文本宽度自适应
pre {
white-space: pre-line;
word-wrap: break-word;
}
模糊文本
.blurry-text {
color: transparent;
text-shadow: 0 0 5px rgba(0,0,0,0.5);
}
网页加载动画
loading:after {
overflow: hidden;
display: inline-block;
vertical-align: bottom;
animation: ellipsis 2s infinite;
content: "2026";
}
@keyframes ellipsis {
from {
  width: 2px;
}
to {
  width: 15px;
}
}
窗口漂浮物


  This text will fly

解决 input:text 自动填充变黄的问题
input:-webkit-autofill{
-webkit-box-shadow: 0 0 0px 10000px white inset !important;
box-shadow: 0 0 0px 10000px white inset !important;
}
jQuery部分 返回头部
$("a.top").click(function (e) {
  e.preventDefault();
  $(body).animate({scrollTop: 0}, 800);
});
预加载图片
$.preloadImages = function () {
  for (var i = 0; i < arguments.length; i++) {
    $("").attr("src", arguments[i]);
  }
};
$.preloadImages("img/hover-on.png", "img/hover-off.png");
自动替换加载失败的图片
$("img").on("error", function () {
  $(this).prop("src", "img/broken.png");
});
切换元素的各种样式
$(".btn").hover(function () {
  $(this).addClass("hover");
}, function () {
  $(this).removeClass("hover");
});
禁用/启用提交按钮
$("input[type="submit"]").prop("disabled", true);
$("input[type="submit"]").prop("disabled", false);
组织默认事件
$("a.no-link").click(function (e) {
e.preventDefault();
});
切换动画
//淡入淡出
$(".btn").click(function () {
  $(".element").fadeToggle("slow");
});
//滑入滑出
$(".btn").click(function () {
$(".element").slideToggle("slow");
});
简单的手风琴样式
$("#accordion").find(".content").hide();  //关闭全部标签
$("#accordion").find(".accordion-header").click(function () {
  var next = $(this).next();
  next.slideToggle("fast");
  $(".content").not(next).slideUp("fast");
  return false;
});
调整多个 div 一样高
var $columns = $(".column");
var height = 0;
$columns.each(function () {
  if ($(this).height() > height) {
    height = $(this).height();
  }
});
$columns.height(height);
同链接不同样式
$("a[href^="http"]").attr("target", "_blank");
$("a[href^="//"]").attr("target", "_blank");
$("a[href^="" + window.location.origin + ""]").attr("target", "_self");  //cannot work in IE10
$("a[href$=pdf]").addClass("pdf");
$("a[href$=doc]").addClass("doc");
$("a[href$=xls]").addClass("xls");
通过内容查找元素
var search = $("#search").val();
$("div:not(:contains("" + search + ""))").hide();
当其他元素获得焦点时触发
$(document).on("visibilitychange", function (e) {
  if (e.target.visibilityState === "visible") {
    console.log("Tab is now in view!");
  } else if (e.target.visibilityState === "hidden") {
    console.log("Tab is now hidden!");
  }
});
显示 Ajax 错误信息
$(document).ajaxError(function (e, xhr, settings, error) {
  console.log(error);
});
禁用右键菜单
$(document).ready(function(){
  $(document).bind("contextmenu", function(e){
     e.preventDefault();
  })
})
模拟 placeholder 属性
$(document).ready(function(){
  var $input_text = $("input[type=text]");
  $input_text.val("Enter your words here...");

  var originalValue = input.val();
  input.focus(function(){
    if($.trim(input.val()) == originalValue){
      input.val("");
    }
  }).blur(funtion(){
    if($.trim(input.val()) == ""){
      input.val(originalValue);
    }
  });
});
判断元素是否存在
$(document).ready(function(){
  if($("#id").length){
    //do sth.
  }
});
放大 标签面积
$("div").click(function(){
  window.loaction = $(this).find("a").attr("href");
  return false;
});
根据浏览器大小选择不同的类
$(document).ready(function(){
  $(window).resize(function(){
    if($(window).width() > 1200){
      $("body").addClass("large");
    } else {
      $("body").removeClass("large")
    }
  });
});
自定义伪类选择器
$.extend($.expr[":"], {
  moreThan500px:function(a){
    return $(a).width > 500;
  }
}); //create a pseudo selector ":moreThan500px"
禁用 jQuery 所以动画
$.fx.off = true;
判断鼠标左右键
$("#id").mousedown(function(e){
  switch(e.witch){
    case 1: //left click
      break;
    case 2: //middle click
      break;
    case 3: //right click
      break;
    default: break;
  }
});
回车提交表单
$("input").keyup(function(e){
  if(e.witch == 13 || e.keyCode == 13){
    $("#submit").trigger("click");
  }
});
配置 Ajax 的全局参数
$("#load").ajaxStart(function(){
  showLoading();
  disableButton();
}).ajaxComplete(function() {
  hideLoading();
  enableButton();
});
用 siblings() 选择兄弟元素
$("#nav li").click(function(){
  $(this).addClass("active").sibling().removeClass("active");
});
用 Firebug 输出日志
jQuery.log = jQuery.fn.log = function(msg){
  if(console){
    console.log("%s, %o", msg, this);
  }
  return $(this);  //链式调用
}
CSS 钩子
$.cssHooks["borderRadius"] = {
  get: function(ele, computed, extra){
    //Read the value of -moz-border-radius, -webkit-border-radius, -o-border-radius, -ms-border-radius or border-radius depanding on browser.
  }
  set: function(ele, value){
    //Set all the property above.
  }
};
限制 textarea 的文字数量
jQuery.fn.maxLength = function(max){
  this.each(function(){
    var type = this.tagName.toLowerCase();
    var inputType = this.type ? this.type.toLowerCase() : null;
    if(type == "input" && inputType == "text" || inputType == "password"){
      this.maxLength = max;  //use normal length
    } else if(type == "textarea"){
      this.onkeypress = function(e){
        var ob = e || window.event;
        var keyCode = ob.keyCode;
        var hasSelection - document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
        return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !ob.shiftKey && !hasSelection);
      };
      this.onkeyup = function(){
        if(this.value.length > max){
          this.value = this.value.substring(0, max);
        }
      };
    }
  });
};
删除字符串中的 HTML 标签
$.fn.stripHTML = function(){
  var regexp = /<("[^"]*"|"[^"]"|[^"">])*/gi;
  this.each(function(){
    $(this).html($(this).html().replace(regexp, ""));
  });
  return $(this);
}
使用 proxy() 函数代理
$("panel").fadeIn(function(){
  $("panel button").click(function(){
    $(this).fadeOut(); //"this" is button, not panel
  });
  $("panel button").click($.proxy(function(){
    $(this).fadeOut(); //"this" is panel, not button
  }, this));
});
禁用前进后退按钮
$(document).ready(function(){
  window.history.forward(1);
  window.history.forward(-1);
})
javascript 部分 类数组对象转化为数组
function trans(obj){
  return [].slice.call(obj);
}

//以下是 ES6 方法
function trans(obj){
  return Array.from(obj);
}
判断 浏览器 js 版本(鸭式辩型)
//js版本检测
  var JS_ver = [];
(Number.prototype.toFixed)?JS_ver.push("1.5"):false;
([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;
([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;
("".trimLeft)?JS_ver.push("1.8.1"):false;
JS_ver.supports = function()
{
  if (arguments[0])
    return (!!~this.join().indexOf(arguments[0] +",") +",");
  else
    return (this[this.length-1]);
}
console.log("Javascript version supported in this browser: "+ JS_ver.supports());
获取 url 中参数
function getURIData(url){
  var para = url.slice(url.indexOf("?") + 1);
  var reg = /&?(w*)=([%w]*)/g;
  var temp, data = {};
  while(temp = reg.exec(para)){
    data[temp[1]] = window.decodeURIComponent(temp[2]);
  }
  return data;
}
利用 documentFragment 避免多次刷新 DOM
(function createList() {
  var lis = ["first item", "second item", "third item",
  "fourth item", "fith item"];
  var Frag = document.createDocumentFragment();
  while (lis.length) {
    var li = document.createElement("li");
     li.appendChild(document.createTextNode(lis.shift()));
    Frag.appendChild(li);
  }
  document.getElementById("myUL").appendChild(Frag);
})();

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/113921.html

相关文章

  • 常见样式设计DOM操作整理

    摘要:部分为不同链接添加不同样式跨浏览器灰度图动画背景清除浮动方法方法方法将浮动元素用一个不浮动的包裹起来表格宽度自适应任意阴影文本宽度自适应模糊文本网页加载动画 css部分 为不同链接添加不同样式 a[href^=http]{ padding-right: 20px; background: url(external.gif) no-repeat center right; } /* em...

    fnngj 评论0 收藏0
  • 常见样式设计DOM操作整理

    摘要:部分为不同链接添加不同样式跨浏览器灰度图动画背景清除浮动方法方法方法将浮动元素用一个不浮动的包裹起来表格宽度自适应任意阴影文本宽度自适应模糊文本网页加载动画 css部分 为不同链接添加不同样式 a[href^=http]{ padding-right: 20px; background: url(external.gif) no-repeat center right; } /* em...

    Forelax 评论0 收藏0
  • 一张脑图看懂BUI Webapp移动快速开发框架【上】--框架与工具、资源

    摘要:后续我们还会增加一些实战类的移动开发案例,欢迎关注专栏。进入官网新版预览在线预览需要使用开启设备模拟,效果更佳。 前言 之前写过一篇 2018开发最快的Webapp框架--BUI交互框架 ,如果你还没看过,可以简单看一下,主要介绍了BUI的基本功能,有多少控件,以及实现的思路,BUI 1.5版本以后变化很大,统一新的风格,新的规范750,新增基于Dom的数据驱动,完善了页面的生命周期等...

    wuyumin 评论0 收藏0
  • 前端开发知识点整理

    摘要:前言本文主要是有关前端方面知识按照目前的认知进行的收集归类概括和整理,涵盖前端理论与前端实践两方面。 前言:本文主要是有关前端方面知识按照 XX 目前的认知进行的收集、归类、概括和整理,涵盖『前端理论』与『前端实践』两方面。本文会告诉你前端需要了解的知识大致有什么,看上去有很多,但具体你要学什么,还是要 follow your heart & follow your BOSS。 初衷...

    Blackjun 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<