Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

读写CSS #11

Open
zhaozy93 opened this issue Jul 4, 2017 · 0 comments
Open

读写CSS #11

zhaozy93 opened this issue Jul 4, 2017 · 0 comments

Comments

@zhaozy93
Copy link
Owner

zhaozy93 commented Jul 4, 2017

页面总离不开样式,样式又离不开css。尽管我们会尽可能的想到各种伪类、各种状态、各种类名切换来完成一些基本的交互样式修改,但总还是需要直接js来操作css,毕竟这样是最灵活的。

这一篇作为对之前css属性那篇的贴补。同时,本篇大部分内容取自于张鑫旭的获取元素CSS值之getComputedStyle方法熟悉, 不过好记性不如烂笔头,还是想自己再实际操作一遍。

获取 css 方法

  • element.offsetWidth/offsetHeight/clientWidth/clientHeight
  • window.getComputedStyle()
  • element.currentStyle()
  • getPropertyValue()
  • getAttribute()
  • getPropertyCSSValue()
  • element.style
  • element.getBoundingClientRect()

element.attrs

这是写法上最简单的,直接将dom元素当作对象,然后css属性作为对象的属性,直接取出来,但是限制特别大,只能取到有限的几个属性。
for in dom来查看,再各个浏览器上,属性的个数和具体属性可能不一致。文章最后列出了chrome和ie8下的属性列表。

这里面给出的信息也极为有限,可能关心的也就是offset和client开头的几个属性,还好这几个属性都被支持了。关于这几个属性的具体用法可以看这里

getComputedStyle

这个是重头戏。他告诉我们的是一个元素在浏览器当前状态下真正的、计算过的、被展示所用到的所有css属性。返回的是一个[object CSSStyleDeclaration]。
let style = window.getComputedStyle(element, [pseudoElt]);。不过真不幸,CSSStyleDeclaration这个对象在各个浏览器上面的属性也不一样,也就是各个浏览器对css属性支持的状况,最烂的肯定是IE,哈哈。同样 最后附录了IE8和Chrome的属性列表。 可惜的是CSSStyleDeclaration属性是只读的,意味着我们不能对其进行操作。

那么来看一下如何获取CSSStyleDeclaration对象,正确姿势是window.getComputedStyleMDN。为了兼容性,我们可以人为的设置第二个属性为null。但是jQuery确是document.defaultView.getComputedStyle,这是为了解决一个firefox的bug,但其实document.defaultView获取的也正是windowMDN(又不兼容IE8及其以下)。没有关系这不重要。更重要的是window.getComputedStyle也不被IE8兼容,但IE实现了element.currentStyle方法。

获取到了CSSStyleDeclaration对象,下一步是如何读取属性的时候了。 可以用CSSStyleDeclaration.cssText转成字符串,自己进去正则匹配,想法不错。也可以CSSStyleDeclaration.getPropertyValue(property),property需要传入非驼峰的写法即background-color。 那IE下怎么处理呢,CSSStyleDeclaration.getAttribute(property),不过有一点区别就是,property需要驼峰写法,IE8测试折现background-color没有通过,backgroundColor可行。

CSSStyleDeclaration.getAttribute(property)CSSStyleDeclaration.getPropertyValue(property)返回的数据格式也是不一样的,比如字体设置为2em,再chrome返回的是转换后px为单位,但IE直接返回2em。这里面的区别可能就要根据属性去慢慢辨别了。

element.style

The HTMLElement.style property is used to get as well as set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute. 这是MDN的定义,这个返回也是一个CSSStyleDeclaration对象,属性尽管没有减少,但发现大部分值都是空字符串,那是因为它只返回inline style,即行内style,而且真是生效的不一定是这里面的属性。更多内容看css

getBoundingClientRect

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.。这个属性返回的是一个包含元素尺寸和位置信息的对象,没有更多的css信息,但因为它也包含了尺寸、位置信息,因此也算作获取css属性的一种方法。

写css方法

  • element.style.property = value
  • element.setAttribute('style','inline-style');
  • element.style.setProperty('color', 'green', 'important');
  • element.style.cssText ='color:red;line-height:30px';
  • element.style.removeProperty('color');
  • document.styleSheets[0].cssRules[0]
  • var style1 = document.createElement('style'); style1.innerHTML = 'body{color:red}#top:hover{background-color: red;color: white;}'; document.head.appendChild(style1);

element.style.prototype element.style.setProperty('color', 'green', 'important')、element.style.setAttribute('background', 'red')

这两个很类似啊, 一般都挺好用
setProperty最低支持IE版本为IE9, IE8及其以下需要使用setAttribute

element.setAttribute('style','inline-style')

这个的坏处是可能会覆盖原本的inline style
setAttribute查找资料显示IE6+以上都被支持,但document.getElementById('div').setAttribute("style","display:none")这个测试在IE8没通过。诶、不知道为什么诶

element.style.cssText ='color:red;line-height:30px'

这个尽量不要使用,会清空当前所有css属性, 但可以作为一个快速清空选项 element.style.cssText =''
但是这个兼容性不错,IE8也被支持

element.style.removeProperty('color')

仅仅作为一个删除某属性的方法

document.styleSheets[0].cssRules[0]

看都不想看的方法。。。。可能在做动画的时候会用到吧。 不太清楚

新建style标签

这个方法好厉害。

附录

element.attrs列表

chrome 59.0.3071.115下一共227个属性
align title lang translate dir dataset hidden tabIndex accessKey draggable spellcheck contentEditable isContentEditable offsetParent offsetTop offsetLeft offsetWidth offsetHeight style innerText outerText onabort onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextmenu oncuechange ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onresize onscroll onseeked onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting click focus blur onauxclick ongotpointercapture onlostpointercapture onpointercancel onpointerdown onpointerenter onpointerleave onpointermove onpointerout onpointerover onpointerup namespaceURI prefix localName tagName id className classList slot attributes shadowRoot assignedSlot innerHTML outerHTML scrollTop scrollLeft scrollWidth scrollHeight clientTop clientLeft clientWidth clientHeight onbeforecopy onbeforecut onbeforepaste oncopy oncut onpaste onsearch onselectstart onwheel onwebkitfullscreenchange onwebkitfullscreenerror previousElementSibling nextElementSibling children firstElementChild lastElementChild childElementCount hasAttributes getAttribute getAttributeNS setAttribute setAttributeNS removeAttribute removeAttributeNS hasAttribute hasAttributeNS getAttributeNode getAttributeNodeNS setAttributeNode setAttributeNodeNS removeAttributeNode closest matches webkitMatchesSelector attachShadow getElementsByTagName getElementsByTagNameNS getElementsByClassName insertAdjacentElement insertAdjacentText insertAdjacentHTML requestPointerLock getClientRects getBoundingClientRect scrollIntoView scrollIntoViewIfNeeded createShadowRoot getDestinationInsertionPoints animate remove webkitRequestFullScreen webkitRequestFullscreen querySelector querySelectorAll setPointerCapture releasePointerCapture hasPointerCapture before after replaceWith prepend append ELEMENT_NODE ATTRIBUTE_NODE TEXT_NODE CDATA_SECTION_NODE ENTITY_REFERENCE_NODE ENTITY_NODE PROCESSING_INSTRUCTION_NODE COMMENT_NODE DOCUMENT_NODE DOCUMENT_TYPE_NODE DOCUMENT_FRAGMENT_NODE NOTATION_NODE DOCUMENT_POSITION_DISCONNECTED DOCUMENT_POSITION_PRECEDING DOCUMENT_POSITION_FOLLOWING DOCUMENT_POSITION_CONTAINS DOCUMENT_POSITION_CONTAINED_BY DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC nodeType nodeName baseURI isConnected ownerDocument parentNode parentElement childNodes firstChild lastChild previousSibling nextSibling nodeValue textContent hasChildNodes getRootNode normalize cloneNode isEqualNode isSameNode compareDocumentPosition contains lookupPrefix lookupNamespaceURI isDefaultNamespace insertBefore appendChild replaceChild removeChild addEventListener removeEventListener dispatchEvent

IE8下 一共157个
nextSibling onresizeend onrowenter aria-haspopup childNodes ondragleave canHaveHTML onbeforepaste ondragover onbeforecopy aria-disabled onpage recordNumber previousSibling nodeName onbeforeactivate accessKey currentStyle scrollLeft onbeforeeditfocus oncontrolselect aria-hidden onblur hideFocus clientHeight style onbeforedeactivate dir aria-expanded onkeydown nodeType ondragstart onscroll onpropertychange ondragenter id aria-level onrowsinserted scopeName lang onmouseup aria-busy oncontextmenu language scrollTop offsetWidth onbeforeupdate onreadystatechange onmouseenter filters onresize isContentEditable aria-checked aria-readonly oncopy onselectstart scrollHeight onmove ondragend onrowexit lastChild aria-secret onactivate canHaveChildren onfocus onfocusin isMultiLine onmouseover offsetTop oncut parentNode tagName className onmousemove title role behaviorUrns onfocusout onfilterchange disabled parentTextEdit ownerDocument offsetParent aria-posinset ondrop ondblclick onrowsdelete tabIndex onkeypress aria-relevant onlosecapture innerText aria-live parentElement ondeactivate aria-labelledby aria-pressed children ondatasetchanged ondataavailable aria-invalid onafterupdate nodeValue onmousewheel onkeyup readyState onmovestart aria-valuenow aria-selected onmouseout aria-owns aria-valuemax onmoveend contentEditable document firstChild sourceIndex outerText isTextEdit isDisabled oncellchange runtimeStyle scrollWidth aria-valuemin onlayoutcomplete onhelp attributes offsetHeight onerrorupdate onmousedown clientTop aria-setsize clientWidth onpaste tagUrn onmouseleave onclick outerHTML ondrag aria-controls onresizestart aria-flowto ondatasetcomplete aria-required clientLeft aria-describedby all onbeforecut innerHTML aria-activedescendant aria-multiselectable offsetLeft align dataSrc dataFld noWrap dataFormatAs

CSSStyleDeclaration属性列表

chrome 59.0.3071.115下一共282个
animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width bottom box-shadow box-sizing break-after break-before break-inside caption-side clear clip color content cursor direction display empty-cells float font-family font-kerning font-size font-stretch font-style font-variant font-variant-ligatures font-variant-caps font-variant-numeric font-weight height image-rendering isolation justify-items justify-self left letter-spacing line-height list-style-image list-style-position list-style-type margin-bottom margin-left margin-right margin-top max-height max-width min-height min-width mix-blend-mode object-fit object-position offset-distance offset-path offset-rotate offset-rotation opacity orphans outline-color outline-offset outline-style outline-width overflow-anchor overflow-wrap overflow-x overflow-y padding-bottom padding-left padding-right padding-top pointer-events position resize right speak table-layout tab-size text-align text-align-last text-decoration text-decoration-line text-decoration-style text-decoration-color text-decoration-skip text-underline-position text-indent text-rendering text-shadow text-size-adjust text-overflow text-transform top touch-action transition-delay transition-duration transition-property transition-timing-function unicode-bidi vertical-align visibility white-space widows width will-change word-break word-spacing word-wrap z-index zoom -webkit-appearance backface-visibility -webkit-background-clip -webkit-background-origin -webkit-border-horizontal-spacing -webkit-border-image -webkit-border-vertical-spacing -webkit-box-align -webkit-box-decoration-break -webkit-box-direction -webkit-box-flex -webkit-box-flex-group -webkit-box-lines -webkit-box-ordinal-group -webkit-box-orient -webkit-box-pack -webkit-box-reflect column-count column-gap column-rule-color column-rule-style column-rule-width column-span column-width align-content align-items align-self flex-basis flex-grow flex-shrink flex-direction flex-wrap justify-content -webkit-font-smoothing grid-auto-columns grid-auto-flow grid-auto-rows grid-column-end grid-column-start grid-template-areas grid-template-columns grid-template-rows grid-row-end grid-row-start grid-column-gap grid-row-gap -webkit-highlight hyphens -webkit-hyphenate-character -webkit-line-break -webkit-line-clamp -webkit-locale -webkit-margin-before-collapse -webkit-margin-after-collapse -webkit-mask-box-image -webkit-mask-box-image-outset -webkit-mask-box-image-repeat -webkit-mask-box-image-slice -webkit-mask-box-image-source -webkit-mask-box-image-width -webkit-mask-clip -webkit-mask-composite -webkit-mask-image -webkit-mask-origin -webkit-mask-position -webkit-mask-repeat -webkit-mask-size order perspective perspective-origin -webkit-print-color-adjust -webkit-rtl-ordering shape-outside shape-image-threshold shape-margin -webkit-tap-highlight-color -webkit-text-combine -webkit-text-decorations-in-effect -webkit-text-emphasis-color -webkit-text-emphasis-position -webkit-text-emphasis-style -webkit-text-fill-color -webkit-text-orientation -webkit-text-security -webkit-text-stroke-color -webkit-text-stroke-width transform transform-origin transform-style -webkit-user-drag -webkit-user-modify user-select -webkit-writing-mode -webkit-app-region buffered-rendering clip-path clip-rule mask filter flood-color flood-opacity lighting-color stop-color stop-opacity color-interpolation color-interpolation-filters color-rendering fill fill-opacity fill-rule marker-end marker-mid marker-start mask-type shape-rendering stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width alignment-baseline baseline-shift dominant-baseline text-anchor writing-mode vector-effect paint-order d cx cy x y r rx ry caret-color

IE8下 一共127个
backgroundColor minWidth widows borderColor fontStyle styleFloat borderLeftColor scrollbarFaceColor unicodeBidi borderBottomWidth direction borderBottomStyle height layoutGridMode outlineColor listStylePosition textOverflow marginLeft letterSpacing backgroundPositionX backgroundPositionY maxHeight listStyleType outlineWidth borderRightStyle margin padding borderCollapse textJustifyTrim fontWeight msInterpolationMode emptyCells hasLayout paddingLeft lineHeight wordSpacing scrollbarTrackColor boxSizing marginTop textAlignLast imeMode zoom lineBreak verticalAlign wordWrap backgroundRepeat zIndex borderRightWidth bottom borderTopStyle pageBreakInside pageBreakBefore minHeight overflowX overflowY scrollbarShadowColor paddingTop textJustify display textTransform borderRightColor rubyPosition scrollbar3dLightColor clipRight maxWidth paddingBottom clipBottom layoutGridChar layoutGridType scrollbarBaseColor paddingRight orphans borderTopWidth marginRight accelerator tableLayout borderStyle textAlign filter borderBottomColor layoutFlow borderTopColor right fontSize outline textAutospace fontFamily pageBreakAfter scrollbarDarkShadowColor borderWidth borderSpacing quotes textUnderlinePosition blockDirection rubyOverhang cursor borderLeftStyle backgroundAttachment listStyleImage rubyAlign scrollbarHighlightColor clipLeft layoutGridLine textKashida width wordBreak textDecoration captionSide outlineStyle scrollbarArrowColor writingMode overflow msBlockProgression visibility top marginBottom color left clipTop behavior borderLeftWidth textKashidaSpace position backgroundImage clear textIndent whiteSpace

@zhaozy93 zhaozy93 mentioned this issue May 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant