如何使用Jquery在mouseleave函数下正确插入click事件

时间:2019-01-28 06:33:29

标签: javascript jquery

我正在尝试执行“鼠标离开”功能,当我离开指定的div并在其侧面单击鼠标时,它将触发我需要的事件。

这是我所做的代码,但是由于我将其设置为某种方式,因此它不起作用。

<script type="text/javascript">

    jQuery(document).ready(function($) {

        $('#Side-Div1').bind('mouseleave', function() {
            $('body').click(function(e){
                if(e.target.className !== '#Side-Div1'){
                    if($('#Side-Div1').is(":visible")){
                           $('.side-nav').fadeToggle('fast','linear');
                           $('body').removeAttr('style');
                           $('html,body').removeClass('overflow-hidden');
                    }
                }
            }        
        });
    })

</script>

我想念的东西是否有一种适当的逻辑设置方式来在一个函数中执行此事件。

4 个答案:

答案 0 :(得分:0)

您是否尝试过以下方法:

 $('#Side-Div1').mouseleave(function() {

这是带有示例的官方文档: https://api.jquery.com/mouseleave/

编辑:我不确定它是否可以按照您希望的方式工作。

答案 1 :(得分:0)

作为您的jquery选择器$('#Side-Div1'),Side-Div1必须是一个ID,而不是类名。对于按类选择元素,应为:

$('.Side-Div1') 

答案 2 :(得分:0)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>

$(document).mouseup(function(e) 
{
    var container = $("#Side-Div1");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
       alert('Do whatever you want.');
        
    }
});
</script>
</head>
<body>

<div id="Side-Div1"><p>Click here or outside this to test this functionality</p></div>

</body>
</html>

如果适用,请使用以下代码。仅当您在此div之外单击时,此功能才有效;如果您在此div上单击,它将不起作用。希望它会对您有所帮助。

    $(document).mouseup(function(e) {
      var container = $("#Side-Div1");
      if (!container.is(e.target) && container.has(e.target).length === 0) 
      {
       //alert('Do whatever you want.');
         $('.side-nav').fadeToggle('fast','linear');
         $('body').removeAttr('style');
         $('html,body').removeClass('overflow-hidden');
      }
    });

答案 3 :(得分:0)

您只需将mouseleave事件绑定到一个布尔变量,然后将click事件附加到主体即可,如下所示:

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Stepper from "@material-ui/core/Stepper";
import Step from "@material-ui/core/Step";
import StepLabel from "@material-ui/core/StepLabel";
import StepContent from "@material-ui/core/StepContent";
import Button from "@material-ui/core/Button";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";

// import Step1 from "./steps/Step1";
import Step2 from "./steps/Step2";
import Step3 from "./steps/Step3";

import StepTemplate from "./steps/StepTemplate";
import AsyncValidationForm from "./forms/AsyncValidationForm";

const styles = theme => ({
  root: {
    width: "90%"
  },
  button: {
    marginTop: theme.spacing.unit,
    marginRight: theme.spacing.unit
  },
  actionsContainer: {
    marginBottom: theme.spacing.unit * 2
  },
  resetContainer: {
    padding: theme.spacing.unit * 3
  }
});

class VerticalLinearStepper extends React.Component {
  state = {
    activeStep: 0,
    //we set our state in this parent
    disabledNext: true,
    username: "",
    password: ""
  };

  steps = {
    //we pass the content of Step1 here, so we dont have to pass props
    "Select campaign settings": props => (
      <StepTemplate
        text={`
        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.

        For each ad campaign that you create, you can control how much you're
        willing to spend on clicks and conversions, which networks and
        geographical locations you want your ads to show on, and more.
    `}
        //we want to apply checking on Step1.js, so we add checkDisabledNext attribute
        checkDisabledNext={true}
        disabledNext={this.state.disabledNext} //use this class' state
        {...props}
      >
        <form>
          form for the first step here
          <div>test here</div>
          <AsyncValidationForm
            onSubmit={values => {
              console.log(values);
              alert(
                `Values: username: ${values.username} password: ${
                  values.password
                }`
              );
            }}
            //we use this class setstate , no need to pass down props
            handleChangeDisabledNext={this.handleChangeDisabledNext}
            disabledNext={this.state.disabledNext}
            handleChange={this.handleChange}
            username={this.state.username}
            password={this.state.password}
          />
        </form>
      </StepTemplate>
    ),
    "Create an ad group": Step2,
    "Create an ad": Step3
  };

  //setState for disabledNext
  handleChangeDisabledNext = value => {
    this.setState({ disabledNext: value });
  };
  //setState for username, password
  handleChange = (name, value) => {
    this.setState({ [name]: value });
  };

  stepsCount = () => Object.values(this.steps).length;

  canGoBack = () => this.state.activeStep > 0;
  canGoForward = () => this.state.activeStep < this.stepsCount();

  isFinished = () => this.state.activeStep === this.stepsCount();

  handleBack = () => {
    if (this.canGoBack()) {
      this.setState(prevState => ({ activeStep: prevState.activeStep - 1 }));
    }
  };

  handleNext = () => {
    if (this.canGoForward()) {
      this.setState(prevState => ({ activeStep: prevState.activeStep + 1 }));
    }
  };

  handleReset = () => this.setState({ activeStep: 0 });

  render() {
    const { classes } = this.props;
    const { activeStep } = this.state;

    return (
      <div className={classes.root}>
        <Stepper activeStep={activeStep} orientation="vertical">
          {Object.entries(this.steps).map(([label, CustomStep]) => (
            <Step key={label}>
              <StepLabel>{label}</StepLabel>
              <StepContent>
                <CustomStep
                  canGoBack={this.canGoBack()}
                  canGoForward={this.canGoForward()}
                  onBack={this.handleBack}
                  onNext={this.handleNext}
                  classes={classes}
                />
              </StepContent>
            </Step>
          ))}
        </Stepper>

        {this.isFinished() && (
          <Paper square elevation={0} className={classes.resetContainer}>
            <Typography>All steps completed - you&apos;re finished</Typography>
            <Button onClick={this.handleReset} className={classes.button}>
              Reset
            </Button>
          </Paper>
        )}
      </div>
    );
  }
}

VerticalLinearStepper.propTypes = {
  classes: PropTypes.object
};

export default withStyles(styles)(VerticalLinearStepper);
var banner = $("#banner-message")
var button = $("button")
var hasMouseLeft = false;


banner.mouseleave(function() {
  hasMouseLeft = true;
  console.log(hasMouseLeft)
})

$('body').click(function() {
  if (hasMouseLeft) {
    // do your magic here
    alert('Mouse has left the div !')
    hasMouseLeft = false;
  } else {
    // do something else or return
    return;
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}