Enable mobile device users to toggle div between `

2019-06-11 00:53发布

问题:

I am just getting back into web design and a ton has changed. I'm going through lots of css tutorials at the moment, and I just read about position: fixed and its problems with mobile browsers.

That is reason enough for me to ignore it and move on to more important things, but I got wondering... what if I had a little "pin" icon that the user could toggle to "un-fix" that element if they found it troublesome for them? Possible?

By "un-fix", yes I mean change it from fixed back to static/default.

And no, not a simple viewport logic setup where mobile can't see it... because "mobile" isn't simply defined. It is only a problem on SOME browsers, so I think it should be left up to the user, mobile or otherwise. Click the pin, it is no longer... well... pinned. That way the aberrant behaviour of certain browsers can be mitigated by the user.

回答1:

To give users the control to manually release a fixed element, here's one simple concept for a solution:

DEMO

HTML

<div id="fixed">
    <h1>Header</h1>
    <p id="release-button"><a href="#">click here to release</a></p>
    <br>
    <p><i>Just an illustration of a concept.
          Not built to toggle. Click 'Run' to refresh.</i></p>
 </div>

CSS

     body { height: 1500px; }

    #fixed {
        width: 95%;
        height: 200px;
        background-color: #ff0;
        border: 1px solid #ccc;
        text-align: center;
        margin: 0;
        padding: 0;
        position: fixed;

    }

    .static {position: static !important;}

jQuery

$('#release-button').click(function() {
    $('#fixed').addClass('static');
});

To provide for an automatic release of a fixed element on a mobile device use media queries:

Example:

footer {
    position: fixed;
}

@media only screen and (max-device-width : 480px) {
    footer {
        position: static; /* or relative */
    }
}