Autor Zpráva
sloncz
Profil
Opět zdravím, sepsal jsem si kód na pohyb divu po stránce do stran, což funguje dobře, ovšem problém nastává v případě, když mi pohybující se div vyjede pryč ze stránky. Uprav by mi prosím někdo daný kód tak, aby se div pohyboval jen po maximální šířce stránky a nezajížděl mimo ní? Předem děkuji


můj kód:

<style>
.div {
left: 0;
top: 0;
background:black;
width:200px;
height:10px;
}
</style>
<div id="plosina" class="div"></div>
<button style="margin-top:50px;width:50px;height:50px;" onMouseUp="stop();" onMouseDown="start(1);"><</button>
<button style="margin-top:50px;width:50px;height:50px;" onMouseUp="stop();" onMouseDown="start(2);">></button>

<script>
var stopka = []
 
function stop() {
    clearInterval(stopka);
}

function start(y) {
        stopka = setInterval(function(){ posun(y) }, 50);
        stopka;
}

var sirka = window.innerWidth/5;
document.getElementById("plosina").style.width = +sirka+"px";

function posun(x){

var elem = document.getElementById("plosina");
var r = elem.getBoundingClientRect();

if(x == 1){ var posun = r.left - 25; } else { var posun = r.left + 25; }

document.getElementById("plosina").style.marginLeft = +posun+"px";
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
jefitto44
Profil
Uprav si html kód takto


<div id="wrapper>
<div id="plosina" class="div"></div>
<button style="margin-top:50px;width:50px;height:50px;" onMouseUp="stop();" onMouseDown="start(1);"><</button>
<button style="margin-top:50px;width:50px;height:50px;" onMouseUp="stop();" onMouseDown="start(2);">></button>
</div>
a CSS

#wrapper {width:100%;position:relative;max-width:100%;}
sloncz
Profil
Bohužel to nepomáhá a stále se dá pomocí javascriptu odjet mimo stránku
Fisir
Profil
Reaguji na sloncza:
Takhle?

function posun(x){
    var elem = document.getElementById('plosina');
    var r = elem.getBoundingClientRect();
    var posun;
    if(x == 1){
        posun = r.left - 25;
    } else {
        posun = r.left + 25;
    }
    if((posun + elem.offsetWidth) > document.body.clientWidth){
        posun = posun - 50;
    } elseif((posun + elem.offsetWidth) < 0){
        posun = posun + 50;
    }
    document.getElementById("plosina").style.marginLeft = posun+'px';
}

(Netestováno.)
sloncz
Profil
Ano, děkuji mnohokrát.

Vaše odpověď


Prosím používejte diakritiku a interpunkci.

Ochrana proti spamu. Napište prosím číslo dvě-sta čtyřicet-sedm:

0