简体   繁体   中英

How can I test if an input's width was set manually?

HTML

<select id="food">
    <option>Pick Favorite Food</option>
    <option>Banana</option>
    <option>Orange</option>
</select>

<select id="place" style="width: 100px;">
    <option>Pick Favorite Place</option>
    <option>Disneyland</option>
    <option>Hawaii</option>
</select>

JavaScript

$('food').getStyle('width'); //56px
$('place').getStyle('width'); //100px

If no width is specified, the browser sizes the input to fit all of the text dynamically. Obviously this has to happen so you can see your elements.

Is there a way to test if the element was styled manually? Either inline, through a stylesheet, or even through JavaScript?

$('food').getWidth(); //false
$('place').getWidth(); //100px

Ryan has the right idea, but since you're using Prototype, you can use readAttribute('style') and trust that the return value came from the style attribute and not through a stylesheet.

Here's a fiddle: http://jsfiddle.net/Q4bRP/

Here's the fiddle's code:

#my-div {
    border: 1px solid green;
    margin-bottom: 10px;
}​

-

<div id="my-div">#my-div, click me</div>
<button id="my-button">add inline style to #my-div</button>

-

$('my-div').on('click', 'div', function(event, el) {
    var styleAttrVal = el.readAttribute('style');
    if (styleAttrVal) {
        alert(styleAttrVal);
    } else {
        alert('no inline style set!');
    }
});

$('my-button').on('click', function(event) {
    $('my-div').setStyle({backgroundColor: 'yellow'});
});​

You can use a Regex on styleAttrVal to test for whatever inline value you're looking for.

Edit: Regarding the last comment above on using a Regex to pull out what you need: You may have some luck looking through Prototype's source to find something you need. They must be doing something similar already for Element.getStyle to work that you may be able to leverage.

You could accomplish this by checking the style attribute on the element. This will only work if the style is set on the element directly, as it is in your example html.

$.fn.getWidth = function(){
    var style = this.attr('style');
    return !~style.indexOf('width') ? false : style.match(/width\s*:\s*(\w+)\s*;/)[1];
}

EDIT:

Aha, better way. This is a case where jQuery tries to be too smart. Use the style attribute on the dom element itself:

$.fn.getWidth = function(){
    var style = this.get(0).style;
    return style.width === '' ? false : style.width; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM